如何将字符串转换为结构数组

How to convert string to struct array

我有一个 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

如何正确地将字符串映射到结构,以便我可以修改 json 的 inStateoutState 值?

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

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

这告诉您 source 字段中(至少一个)似乎有错误的类型:string 而不是可以用 int64 表示的内容。

所以让我们检查一下 stringJson 中的 source 字段:

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

如您所见,第二个 sourcestring 的数组。因此错误。

要解决这个问题,您需要确保 sourceint 的数组。不幸的是,1_16280085889025_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