首页 > 解决方案 > 如何将字符串转换为结构数组

问题描述

我有一个 json 数组,它被转换成一个字符串。现在我想将字符串映射到结构数组,以便我可以修改字符串 json。下面是我的代码库

type ProcessdetailsEntity struct {
    Source   []int64 `json:"source"`
    Node     string  `json:"node"`
    Targets  []int64 `json:"targets"`
    Issave   bool    `json:"isSave"`
    Instate  []int64 `json:"inState"`
    OutState []int64 `json:"outState"`
}

func main() {
    var stringJson = "[{\"source\":[-1],\"node\":\"1_1628008588902\",\"targets\":[],\"isSave\":true,\"inState\":[1],\"outState\":[2]},{\"source\":[\"1_1628008588902\",\"5_1628008613446\"],\"node\":\"2_1628008595757\",\"targets\":[],\"isSave\":true,\"inState\":[2,5],\"outState\":[3,6]}]"
    in := []byte(stringJson)
    detailsEntity := []ProcessdetailsEntity{}
    err := json.Unmarshal(in, &detailsEntity)
    if err != nil {
        log.Print(err)
    }
}

现在,当我运行此代码库时,出现错误:

json: cannot unmarshal string into Go struct field ProcessdetailsEntity.source of type int64

如何正确地将字符串映射到 struct 以便我可以修改 json 的inStateandoutState值?

标签: gounmarshalling

解决方案


你得到的错误已经很明显了:

无法将字符串解组为 int64 类型的 Go struct 字段 ProcessdetailsEntity.source

这告诉您(至少一个)source字段似乎具有错误的类型: astring而不是可以由 a 表示的东西int64

因此,让我们检查您的source字段stringJson

"source":[-1]
"source":["1_1628008588902","5_1628008613446"]

如您所见,第二个sourcestring. 因此错误。

要解决这个问题,您需要确保source是一个int. 不幸的是,1_1628008588902并且5_1628008613446不是 Go 中的有效整数。

我稍微修改了您的 JSON 并修复了您的代码,然后它就可以工作了:

package main

import (
    "encoding/json"
    "log"
)

type ProcessdetailsEntity struct {
    Source   []int64 `json:"source"`
    Node     string  `json:"node"`
    Targets  []int64 `json:"targets"`
    Issave   bool    `json:"isSave"`
    Instate  []int64 `json:"inState"`
    OutState []int64 `json:"outState"`
}

func main() {
    var stringJson = `[
        {
            "source":[-1],
            "node":"1_1628008588902",
            "targets":[],
            "isSave":true,
            "inState":[1],
            "outState":[2]
        },
        {
            "source":[11628008588902,51628008613446],
            "node":"2_1628008595757",
            "targets":[],
            "isSave":true,
            "inState":[2,5],
            "outState":[3,6]
        }
    ]`
    
    in := []byte(stringJson)
    detailsEntity := []ProcessdetailsEntity{}
    err := json.Unmarshal(in, &detailsEntity)
    if err != nil {
        log.Print(err)
    }
}

见: https: //play.golang.org/p/kcrkfRliWJ5


推荐阅读