json.Unmarshal将转换为另一种自定义类型(将map转换为slice)。

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

json.Unmarshal convert to custom another type (map to slice)

问题

给定以下JSON字符串:

{
 "username":"bob",
 "name":"Robert",
 "locations": [
   {
    "city": "Paris",
    "country": "France"
   },
   {
    "city": "Los Angeles",
    "country": "US"
   }
 ]
}

我需要一种将其解组成以下结构的方法:

type User struct {
 Username string
 Name string
 Cities []string
}

其中Cities是一个包含"city"值的切片,而"country"被丢弃。

我认为可以使用自定义的JSON.Unmarshal函数来实现,但不确定如何做到这一点。

英文:

Given the following JSON string:

{
 "username":"bob",
 "name":"Robert",
 "locations": [
   {
    "city": "Paris",
    "country": "France"
   },
   {
    "city": "Los Angeles",
    "country": "US"
   }
 ]
}

I need a way to unmarshal this into the a struct like this:

type User struct {
 Username string
 Name string
 Cities []string
}

Where Cities is a slice containing the "city" values, and "country" is discarded.

I think this can be done using a custom JSON.Unmarshal function, but not sure how to do that.

答案1

得分: 3

你可以为Cities定义新的类型,并实现自定义的Unmarshaler

type User struct {
	Username string   `json:"username"`
	Name     string   `json:"name"`
	Cities   []Cities `json:"locations"`
}

type Cities string

func (c *Cities) UnmarshalJSON(data []byte) error {
	tmp := struct {
		City string `json:"city"`
	}{}
	err := json.Unmarshal(data, &tmp)
	if err != nil {
		return err
	}
	*c = Cities(tmp.City)
	return nil
}

<kbd>PLAYGROUND</kbd>

英文:

You can define new type for Cities and implement custom Unmarshaler:

type User struct {
	Username string   `json:&quot;username&quot;`
	Name     string   `json:&quot;name&quot;`
	Cities   []Cities `json:&quot;locations&quot;`
}

type Cities string

func (c *Cities) UnmarshalJSON(data []byte) error {
	tmp := struct {
		City string `json:&quot;city&quot;`
	}{}
	err := json.Unmarshal(data, &amp;tmp)
	if err != nil {
		return err
	}
	*c = Cities(tmp.City)
	return nil
}

<kbd>PLAYGROUND</kbd>

huangapple
  • 本文由 发表于 2023年5月17日 13:15:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/76268757.html
匿名

发表评论

匿名网友

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

确定