Home >Backend Development >Golang >json.Unmarshal Convert to another custom type (mapped to slice)

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

王林
王林forward
2024-02-09 08:45:181260browse

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"
   }
 ]
}

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

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

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
}

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!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete