donglong1465 2015-05-13 11:56
浏览 13
已采纳

在Go中表示此JSON的最佳方法?

I am writing an endpoint to return data for Geckoboard, it excepts a format like so:

{
  "item": [
    {
      "value": "274057"
    },
    [
      "38594",
      "39957",
      "35316",
      "35913",
      "36668",
      "45660",
      "41949"
    ]
  ]
}

"item" is an array of varying structures. How would I represent this data in Go?

Note: this is not on how I would unmarshal this, I need to generate this format.

  • 写回答

2条回答 默认 最新

  • duandange7480 2015-05-13 12:21
    关注

    This stuff is easier than you might think. It's just not that well documented for the casual reader. I would recommend ffjson over normal json tho. It's made up in such a manner that you don't need to change your syntax other than the library name.

    It's easy as this:

    type User struct {
        Id      int    `json:'id'`
        Name    string `json:name`
        SomeId1 int    `json:some_id_1`
        SomeId2 int    `json:some_id_2`
        SomeId3 int    `json:some_id_3`
        SomeId4 int    `json:some_id_4`
    }
    
    item := map[string]User{}
    for i := 0; i < 10; i++ {
        item[strconv.itoa(i)] = User{i, "Username X", 38393, 29384, 12393, 123981}
    }
    buf, err := ffjson.Marshal(&item)
    

    The downside of structs (even in ffjson still) is that reflection will always be used, which, in times that you're in need of high performance, you will waste a lot of CPU cycles. ffjson is 2-3 times faster than normal json when you keep it to maps. This way the library can compile every data-structure you marshal and re-use it instead of constantly inspecting the data-integrity/structure with reflect.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。