V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
gmlaogong
V2EX  ›  程序员

下面这种 json 字符串 golang 怎么实现通过 map 和 list 结构输出出来呢?

  •  
  •   gmlaogong · 357 天前 · 740 次点击
    这是一个创建于 357 天前的主题,其中的信息可能已经有所发展或是发生改变。
    我是 java 项目中需要 go 输出这种接口的 json 字符串,搞了半天不行,麻烦问一下,怎么实现,在 java 中通过对象和 list 就能实现。go 怎么实现呢?目前外层我用的是 map ,personInfo 这里 list ,但是 list 不好使不知道为什么?
    这里是我写的结构
    data := make(map[string]interface{})
    data["sign_type"] = "sign"
    data["dev_sno"] = "888088"
    data["register_no"] = "888088"
    data["type"] = "1"
    dataPersonInfo := make(map[string]int)
    dataPersonInfo.PushBack(map[string]int{
    "person_type": 4,
    "total": 10,
    })
    dataPersonInfo.PushBack(map[string]int{
    "person_type": 3,
    "total": 5,
    })
    data["personInfo"] = dataPersonInfo
    下面是想要输出的结构
    {
    "sign_type": "sign",
    "dev_sno": "888999",
    "register_no": "888999",
    "type": "1",
    "personInfo": [
    {
    "person_type": 4,
    "total": 10
    },
    {
    "person_type": 3,
    "total": 5
    }
    ]
    }
    FreeEx
        1
    FreeEx  
       357 天前
    把 list 换成 slice 就好了,golang 里面的 list 很少使用。
    willchen
        2
    willchen  
       357 天前
    data := make(map[string]interface{})

    data["sign_type"] = "sign"
    data["dev_sno"] = "888088"
    data["register_no"] = "888088"
    data["type"] = "1"

    dataPersonInfo := make([]map[string]int, 0)

    dataPersonInfo = append(dataPersonInfo, map[string]int{
    "person_type": 4,
    "total": 10,
    })

    dataPersonInfo = append(dataPersonInfo, map[string]int{
    "person_type": 3,
    "total": 5,
    })

    data["personInfo"] = dataPersonInfo
    sunny352787
        3
    sunny352787  
       357 天前
    https://mholt.github.io/json-to-go/

    你可以考虑把 json 贴进去,生成 struct
    gmlaogong
        4
    gmlaogong  
    OP
       356 天前
    @sunny352787 这个我稍后试试,谢谢提供
    @willchen 谢谢可以用
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3165 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 14:40 · PVG 22:40 · LAX 07:40 · JFK 10:40
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.