【问题标题】:Unmarshal json that has multile type data without keyUnmarshal json 具有多种类型的数据,没有键
【发布时间】:2021-12-19 13:54:32
【问题描述】:

假设我有这样的 json:

{
      "a": [
            [
            "aaa",
            15
            ],
            [
            "bbb",
            11
            ]
        ]
    }

我有这个代码:

func main() {
    XJson := `
    {
      "a": [
            [
            "aaa",
            15
            ],
            [
            "bbb",
            11
            ]
        ]
    }`

    var Output StructJson

    json.Unmarshal([]byte(XJson), &Output)

    fmt.Println(Output)
}

type StructJson struct {
    [][]string `json:"a"`  //wrong because have 15 and 11 have int type data
    ///what must i do in here?
}



如何解组? 我的意思是,“aaa”和“bbb”具有数据字符串类型,15 和 11 具有数据整数类型。 如果我使用那个“错误”的结构,输出是

{[[aaa ] [bbb ]]}

【问题讨论】:

  • 使用interface{}:type StructJson struct {A [][]interface{} `json:"a"`}

标签: json go


【解决方案1】:

@ekomonimo 正如@colm.anseo 提到的,为了解决这类问题,我们可以使用interface{}

这里如何使用它:

package main

import (
    "encoding/json"
    "fmt"
    "reflect"
)

func main() {
    XJson := `
    {
      "a": [
            [
            "aaa",
            15
            ],
            [
            "bbb",
            11
            ]
        ]
    }`

    var Output StructJson

    json.Unmarshal([]byte(XJson), &Output)

    fmt.Println("Output:", Output)
    // Prints: aaa string
    fmt.Println("Data on path Output.A[0][0]:", Output.A[0][0], reflect.TypeOf(Output.A[0][0]))
    // Prints: 15 float64
    fmt.Println("Data on path Output.A[0][1]:", Output.A[0][1], reflect.TypeOf(Output.A[0][1]))
}

type StructJson struct {
    A [][]interface{} `json:"a"`
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-28
    • 1970-01-01
    • 2021-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-06
    • 2020-12-21
    相关资源
    最近更新 更多