json.Unmarshal Convert to another custom type (mapped to slice)

王林
Release: 2024-02-09 08:45:18
forward
1213 people have browsed it

json.Unmarshal 转换为自定义的另一种类型(映射到切片)

php editor Apple will introduce you to how to use the json.Unmarshal function to convert JSON data into another custom type, that is, mapped to slices. During the development process, we often encounter situations where we need to convert JSON data into different data types, and the json.Unmarshal function can help us achieve this function. Through the introduction and sample code of this article, I believe readers can better understand and apply the json.Unmarshal function and improve development efficiency and code quality.

Question content

Given the following json string:

{
 "username":"bob",
 "name":"robert",
 "locations": [
   {
    "city": "paris",
    "country": "france"
   },
   {
    "city": "los angeles",
    "country": "us"
   }
 ]
}
Copy after login

I need a way to unmarshal it into a structure like this:

type User struct {
 Username string
 Name string
 Cities []string
}
Copy after login

Where cities is a slice containing the "city" value, "country" is discarded.

I think this can be done using a custom json.unmarshal function, but not sure how.

Workaround

You can define new types for cities and implement custom 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
}
Copy after login

Playground

The above is the detailed content of json.Unmarshal Convert to another custom type (mapped to slice). For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!