M
M
Mikkkch2020-10-03 10:52:49
go
Mikkkch, 2020-10-03 10:52:49

How does Unmarshal determine which structure field to dump data from json into?

There are several entries:

type Masteries []ChampionMastery

type ChampionMastery struct {
    ChampionID                   int
    ChampionLevel                int
    ChampionPoints               int
    LastPlayTime                 int
    ChampionPointsSinceLastLevel int
    ChampionPointsUntilNextLevel int
    ChestGranted                 bool
    TokensEarned                 int
    SummonerID                   string
}

Her json:
[{"championId":157,"championLevel":7,"championPoints":57547,"lastPlayTime":1601655202000,"championPointsSinceLastLevel":35947,"championPointsUntilNextLevel":0,"chestGranted":true,"tokensEarned":0, "summonerId": "qljdJnn2kgOLoNByYPxY7IECDARTZMjNyo4iDskm5vUF55k"}, { "championId": 238, "championLevel": 3, "championPoints": 9406, "lastPlayTime": 1598356873000, "championPointsSinceLastLevel": 3406, "championPointsUntilNextLevel": 3194, "chestGranted": false,"tokensEarned":0,"summonerId":"qljdJnn2kgOLoNByYPxY7IECDARTZMjNyo4iDskm5vUF55k"},

And such
type Rotation struct {
    // Structure that is filled with data after a request for champion-v3
    // Contains IDs for all free champions, IDs for free champions for newbies, etc.
    FreeChampionsIDs               []int `json:"freeChampionIds"`
    FreeChampionsIDsForNewsPlayers []int `json:"freeChampionIdsForNewPlayers"`
    MaxNewPlayerLevel              int   `json:"maxNewPlayerLevel"`
    // More details: https://developer.riotgames.com/apis#champion-v3
}

Her json:
{"freeChampionIds":[20,28,37,42,53,68,80,83,114,157,164,222,236,245,421],"freeChampionIdsForNewPlayers":[18,81,92,141,37,238,19,45,25,64],"maxNewPlayerLevel":10 }


The first and second cases work out correctly, but then the question arises, why put labels on each field of the structure, if unmarshal handles itself and unloads information from json into the appropriate fields?

Here, to make it a little clearer, the result of using Unmarshal to the first structure (indexing was used, so the structure from the list is the first one):
{157 7 57547 1601655202000 35947 0 true 0 qljdJnn2kgOLoNByYPxY7IECDARTZMjNyo4iDskm5vUF55k}

As you can see, even though the fields are not named as they are in json and they do not have labels, everything is loaded correctly.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
U
uvelichitel, 2020-10-03
@uvelichitel

What if you want to serialize the ChampionID to " freeChampionIds " . Then you can

type ChampionMastery struct {
    ChampionID                   int   `json:"freeChampionId"`

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question