doudilin1225 2016-04-30 07:15
浏览 127

如何在Golang中使用Unmarshal从json文档中获取结构中的json字符串

The sample code

package main

import (
    "encoding/json"
    "fmt"
)

type ClassRoom struct {
    Student struct {
        Name string
        /*
           Address struct {
               City string
               Zip  int
           } `json:"address"`
        */
        Address []string `json:"address"` //here, Want to get json string
        Age     int      `json:"age"`
    } `json:"student"`
    ClassCode int `json:"code"`
}

func main() {
    jsonDocs := `[
    {"student":{"name":"jss","address":{"City":"Seoul","Zip":54},"Age":28},"ClassCode":1234}]`

    var node []ClassRoom

    json.Unmarshal([]byte(jsonDocs), &node)
    fmt.Println(node)
}

I want Address variable of json string type (like {"City":"Seoul"....}).

  • 写回答

1条回答 默认 最新

  • duanchai0028 2016-04-30 12:27
    关注

    You need to use json.RawMessage instead of []string, example:

    type ClassRoom struct {
        Student struct {
            Name string
            Address json.RawMessage `json:"address"` //here, Want to get json string
            Age     int             `json:"age"`
        } `json:"student"`
        ClassCode int `json:"code"`
    }
    
    func main() {
        jsonDocs := `[{"student":{"name":"jss","address":{"City":"Seoul","Zip":54},"Age":28},"ClassCode":1234}]`
        var node []ClassRoom
    
        json.Unmarshal([]byte(jsonDocs), &node)
        fmt.Printf("%s
    ", node[0].Student.Address)
    
        var addr struct {
            City string
            Zip  int
        }
        json.Unmarshal(node[0].Student.Address, &addr)
        fmt.Printf("%+v", addr)
    }
    

    <kbd>playground</kbd>

    评论

报告相同问题?

悬赏问题

  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入