Golang:如何将 []string 转换为具有类型的结构体?

huangapple go评论74阅读模式
英文:

Golang: how to cast []string to a typed struct?

问题

使用JSON对象很简单:

type MyObj struct {
    Prop1   int      `json:"prop1"`
    Prop2   []string `json:"prop2"`
}

如何将简单的[]string切片转换为MyObj类型?我知道可以遍历切片并手动将每个属性分配给相应的索引,但也许有更优化的方法,考虑到Prop1在切片的索引0处,而Prop2在索引1处。

编辑1

我的实际JSON字符串看起来像[100, 200]。因此,MyObj.Prop1将被填充为100MyObj.Prop2将被填充为200

谢谢。

英文:

With json objects it's simple:

type MyObj struct {
    Prop1   int      `json:"prop1"`
    Prop2   []string `json:"prop2"`
}

How would I cast simple []string slice against MyObj? I know I could iterate over slice and manually assign each property by respective index, but maybe there's more optimal way, considering that Prop1 references at 0 index of the slice, and Prop2 - 1.

EDIT1:

My actual JSON string looks like [100, 200]. So MyObj.Prop1 would get filled with 100, and MyObj.Prop2 with 200 respectively.

Thank you.

答案1

得分: 3

你需要一个自定义的json.Unmarshaler

type MyObj struct {
    Prop1   int      `json:"prop1"`
    Prop2   int      `json:"prop2"`
}

func (a *MyObj) UnmarshalJSON(b []byte) error {
    s := []string{}
    
    if err := json.Unmarshal(b, &s); err != nil {
        return err
    }
    
    l := len(s)
    
    // 检查切片边界和错误!!
    a.Prop1, _ = strconv.Atoi(s[0])
    a.Prop2, _ = strconv.Atoi(s[l-1])
    
    return nil
}

示例:https://play.golang.org/p/fVobgtrqNw

英文:

You'll need a custom json.Umnarshaller:

type MyObj struct {
    Prop1   int      `json:"prop1"`
    Prop2   int      `json:"prop2"`
}

func (a *MyObj) UnmarshalJSON(b []byte) error {
	s := []string{}
	
	if err := json.Unmarshal(b, &s); err != nil {
		return err
	}
	
	l := len(s)
	
    // Check slice bounds and errors!!
	a.Prop1, _ = strconv.Atoi(s[0])
    a.Prop2, _ = strconv.Atoi(s[l-1])
	
	return nil
}

Example: https://play.golang.org/p/fVobgtrqNw

答案2

得分: 2

给定你将json作为字符串存储在一个变量中(yourString),然后你可以将其解析为[]MyObj。

yourString := `{"prop1":"100","prop2":"200"}`
var myObj MyObj
err := json.Unmarshal([]byte(yourString), &myObj)
if err == nil {
    fmt.Printf("%+v\n", myObj)
} else {
    fmt.Println(err)
    fmt.Printf("%+v\n", myObj)
}

或者你可以使用json.decode来实现:

yourString := `{"a" : ["prop1":100,"prop2":["200"]}`
var myObj MyObj
err := json.NewDecoder(strings.NewReader(yourString)).Decode(&myObj)
if err != nil {
    fmt.Println(err)
    return
}
fmt.Println(myObj.Prop1)
fmt.Println(myObj.Prop2)

更新

根据你定义的MyObj,你的json应该是这样的:{"prop1":100,"prop2":["200"]}。由于prop1是一个整数,prop2是一个字符串数组,我认为你需要更改你的结构体或者更改你的json。

例如,你可以像这样定义你的MyObj:

type MyObj struct {
    Prop1   int      `json:"prop1"`
    Prop2   string   `json:"prop2"`
}

以匹配这样的json对象:

{"prop1":100,"prop2":"200"}

如果你想保持MyObj不变,那么你的json应该是这样的:

{"prop1":100,"prop2":["200"]}

在go playground中检查:https://play.golang.org/p/yMpeBbjhkt

英文:

Given that you have your json as a string in a variable (yourString) then you can Unmarshall that into your []MyObj

yourString := `{"prop1":"100","prop2":"200"}`
var myObj MyObj
err := json.Unmarshal([]byte(yourString), &myObj)
if err == nil {
    fmt.Printf("%+v\n", myObj)
} else {
    fmt.Println(err)
    fmt.Printf("%+v\n", myObj)
}

Alternatively you can do this using json.decode:

yourString := `{"a" : ["prop1":100,"prop2":["200"]}`
var myObj MyObj
err := json.NewDecoder(strings.NewReader(yourString)).Decode(&myObj)
if err != nil {
    fmt.Println(err)
    return
}
fmt.Println(myObj.Prop1)
fmt.Println(myObj.Prop2)

Update

According to the MyObj you defined, your json should look like this: {"prop1":100,"prop2":["200"]}. Since prop1 is an int, and prop2 is a []string
I think you either need to change your struct or change your json.

For instance you could define your MyObj like this:

type MyObj struct {
    Prop1   int      `json:"prop1"`
    Prop2   string   `json:"prop2"`
}

To match a json object like this:

> {"prop1":100,"prop2":"200"}

If you want to keep MyObj as it is then your json should look like this:

> {"prop1":100,"prop2":["200"]}

Check in the go playground: https://play.golang.org/p/yMpeBbjhkt

huangapple
  • 本文由 发表于 2017年5月12日 16:12:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/43932693.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定