duanpen9294 2019-03-28 22:43
浏览 63
已采纳

如何在多对象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条回答 默认 最新

  • duanqiang2977 2019-03-28 23:37
    关注

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!