dousao6260 2017-01-27 18:32 采纳率: 0%
浏览 14
已采纳

无法将JSON解组到结构中

I want to unmarshal the following JSON into a struct:

{"MAIN":{"data":[{"KEY1":"1111111","KEY2":"2222222","KEY3":0,"KEY4":"AAAAAAA","KEY5":"9999","KEY6":"4","KEY7":"BBBBBBB"}]}}

I have tried to modify the jsonStruct in various ways, but the struct is always empty:

package main

import (
    "encoding/json"
    "fmt"
)

type jsonStruct struct {
    main struct {
        data []struct {
            Key1 string `json:"KEY1"`
            Key2 string `json:"KEY2"`
            Key3 int    `json:"KEY3"`
            Key4 string `json:"KEY4"`
            Key5 string `json:"KEY5"`
            Key6 string `json:"KEY6"`
            Key7 string `json:"KEY7"`
       } `json:"data"`
    } `json:"MAIN"`
}

func main() {
    jsonData := []byte(`{"MAIN":{"data":[{"KEY1":"1111111","KEY2":"2222222","KEY3":0,"KEY4":"AAAAAAA","KEY5":"9999","KEY6":"4","KEY7":"BBBBBBB"}]}}`)

    var js jsonStruct

    err := json.Unmarshal(jsonData, &js)
    if err != nil {
            panic(err)
    }

    fmt.Println(js)
}

Output:

{{[]}}

The JSON I have worked with in the past contained no brackets, so I suspect that the problem is related to them.

Can anyone help?

https://play.golang.org/p/pymKbOqcM-

  • 写回答

1条回答 默认 最新

  • duanqin4238 2017-01-27 19:09
    关注

    This is happening because other packages (encoding/json) can't access private fields (even with reflection). In go, private fields are fields starting with a lower case character. To fix this, make your struct contains public fields (which start with an upper case letter):

    type jsonStruct struct {
        Main struct {
            Data []struct {
                Key1 string `json:"KEY1"`
                Key2 string `json:"KEY2"`
                Key3 int    `json:"KEY3"`
                Key4 string `json:"KEY4"`
                Key5 string `json:"KEY5"`
                Key6 string `json:"KEY6"`
                Key7 string `json:"KEY7"`
           } `json:"data"`
        } `json:"MAIN"`
    }
    

    https://play.golang.org/p/lStXAvDtpZ

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用