简体   繁体   中英

Json unmarshalling in GO

I am trying to unmarshal a json response from the server into various types, but I am not finding how to do it.

The types which work are :-

type ServerResponse struct {
  Total int
  Data  []User
}

type User struct {
  Name  string
  Age   int
}

and I can successfully unmarshal the json and receive the expected User type.

What I want to do is handle various server responses and convert after the fact. eg.

type ServerResponse struct {
  Total int
  Data  []ServerItem
}

type User struct {
  ServerItem
  Name  string
  Age   int
}

type Book struct {
  ServerItem
  Name      string
  Author    string
}

Then use either User(response.Data) or response.Data.(User) to make it a concrete type so that later functions type check correctly.

Please could anyone let me know where to start looking to solve this issue.

I don't think that this can be done easily. Just decode to map[string]interface{} and create your stuff from this.

Here I wrote a simple program that parses json http://play.golang.org/p/51eiswgznR .

You may also want to read the encoding/json docs http://golang.org/pkg/encoding/json/

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