简体   繁体   中英

Unmarshalling a json array in golang

I have a question regarding the golang unmarshalling . I was trying to unmarshal Json array but it is giving nil result for one decoding while it is successful in the other. I don't understand the reason behind it. Is it a mistake in the code or expected?

package main

import "fmt"
import "encoding/json"

type PublicKey struct {
    Id int
    Key string
}

type KeysResponse struct {
    Collection []PublicKey
}

func main() {
    keysBody := []byte(`[{"id": 1,"key": "-"},{"id": 2,"key": "-"},{"id": 3,"key": "-"}]`)
    keys := make([]PublicKey,0)

    json.Unmarshal(keysBody, &keys)//This works
    fmt.Printf("%#v\n", keys)
    response := KeysResponse{}
    json.Unmarshal(keysBody, &response)//This doesn't work
    fmt.Printf("%#v\n", response)

}

http://play.golang.org/p/L9xDG26M8-

That's not expected to work. What you have in the json is an array of type PublicKey . The KeysResponse type would be used for json looking like this;

{
   "Collection": [{"id": 1,"key": "-"},{"id": 2,"key": "-"},{"id": 3,"key": "-"}]
}

Which is not what you have. If you want the data to be stored in that type I'd recommend the following; response := KeysResponse{keys} on the line after you unmarshal into keys .

To elaborate on that distinction. In the working case the json is just an array with objects inside of it. The json I wrote above is an object which has a single property named Collection which is of type array and the objects in the array are represented by the PublicKey type (objects with an int called id and a string called key). When working on code to unmarshal json, it's helpful to describe the structure using plain English like this, it tells you precisely what types/structures you need in Go to hold the data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM