如何在多对象JSON数组中编码/封送来自我的服务器的响应

I am trying to format my response from a server in an array of multiple object JSON. I tried slice and []Struct but I believe I am not able to understand their usage correctly.

I tried the method mentioned here - https://play.golang.org/p/9OEPzbf0Me0 but didn't work in my case

I am using golang to get response for a query parameter

router.HandleFunc("/v1.0/singles", GetInfo).Methods("GET").Queries("Group", "{group}")

//controller.go

func SendToServer(jsonValue []byte, command string) (models.JSON, error) {

    var pdatar models.JSON
    s := []string{"http://172.xx.xxx.xx:xxxxx/", command}

    response, err := http.Post(strings.Join(s, ""), "application/json", bytes.NewBuffer(jsonValue))

    data, err := ioutil.ReadAll(response.Body)

    err = json.Unmarshal(data, &pdatar)

    mdatar := make(models.JSON)
    mdatar["ID"] = pdatar["id"]
    mdatar["Name"] = pdatar["name"]

    fmt.Println(mdatar) //This is how it is coming map[ID:[877,235], Name:[FCU, GHP]]

    /*Another attempt

               var temp models.Arr
           json.Unmarshal(data, &temp)
           fmt.Println(temp) ---- returning null

    */
    return mdatar, nil
}

func (c Controller) GetSingle(pdata models.Single) (models.JSON, error) {

    mdata := make(models.JSON)
    mdata["group"] = pdata.Group

    jsonValue, err := json.Marshal(mdata)

    pdatar, err := SendToServer(jsonValue, "func_info")

    return pdatar, nil

    // json.NewEncoder(w).Encode(pdatar) //sending this to my main function

}

//model.go

type JSON map[string]interface{}

type Single struct {
    ID   int    `json:"id"`
    Name string `json:"name"`
}

type Data []Single
type Arr [][]string

I have a response from my API in a format

    {

    "id":[877,235,312,429],
    "name" ["FCU","GHP","c","d"],
    "group":["x","x","y","z"] 
    }

With Current Code I am receiving a response

{"id":[877 235], "name": ["FCU" "GHP"] 

Though I am expecting a response

{ 

  "data":
    [
       {"id": 877
         "name" : "FCU"
        }

       {"id": 235
         "name": "GHP"
        }


   ]
}

1个回答



您的mdatarr不会更改任何格式,因此此结果很有意义。</ p>

如果 从服务器收到的数据的格式为:</ p>

  {
“ id”:[877,235,312,429],
“ name” [“ FCU”,“ GHP”, “ c”,“ d”],
“ group”:[“ x”,“ x”,“ y”,“ z”]
}
</ code> </ pre>

< p>然后您需要翻译它。 理想情况下,您需要对服务器进行修复,以使其以以下格式发送数据:</ p>

  {
{
“ id”:877,
“ name”:“ FCU “,
” group“:” x“,
},
...
}
</ code> </ pre>

如果服务器可以发送类似上面的内容 ,那么您只需将其编组为models.Data对象即可。</ p>

如果这不是一个选择,并且您确实需要在客户端进行翻译,那么您需要 for循环执行以下操作:</ p>

  ids:= pdatarr [“ id”] 
names:= pdatarr [“ name”]
...

if len(ids)!= len(names){
返回nil,错误。New(“无效的输入格式”)
}

var mdatar模型。Data
for i:= range(ids){
mdatar = append(mdatar,models.Single {ids [i],names [i],...})
}

返回模型。JSON{“ data”:mdatar},nil
</ code> < / pre>
</ div>

展开原文

原文

Your mdatarr doesn't change the format any, so this result makes sense.

If the data received from the server is in the format:

{
  "id":    [877,235,312,429],
  "name"   ["FCU","GHP","c","d"],
  "group": ["x","x","y","z"] 
}

then you will need translate it. Ideally you'd fix the server so that it sends data in the format:

{
  {
    "id": 877,
    "name": "FCU",
    "group": "x",
  },
  ...
}

If the server could send something like the above, then you could simply unmarshal it into a models.Data object.

If that is not an option, and you really need to do the translation client-side, then you'll need a for loop that does something like this:

ids := pdatarr["id"]
names := pdatarr["name"]
...

if len(ids) != len(names) {
  return nil, errors.New("Invalid input format")
}

var mdatar models.Data
for i := range(ids) {
  mdatar = append(mdatar, models.Single{ids[i], names[i], ...})
}

return models.JSON{"data": mdatar}, nil

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐