Json unmarshalling in GO

huangapple go评论84阅读模式
英文:

Json unmarshalling in GO

问题

我正在尝试将服务器返回的JSON响应解组成不同的类型,但是我找不到如何做到这一点。

可以正常工作的类型是:

type ServerResponse struct {
  Total int
  Data  []User
}

type User struct {
  Name string
  Age  int
}

我可以成功地解组JSON并获得预期的User类型。

我想做的是处理各种服务器响应并在之后进行转换。例如:

type ServerResponse struct {
  Total int
  Data  []ServerItem
}

type User struct {
  ServerItem
  Name string
  Age  int
}

type Book struct {
  ServerItem
  Name   string
  Author string
}

然后,可以使用User(response.Data)response.Data.(User)将其转换为具体类型,以便稍后的函数正确进行类型检查。

请问有人可以告诉我从哪里开始解决这个问题吗?

英文:

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.

答案1

得分: 1

我不认为这可以轻松地完成。只需解码为map[string]interface{},然后根据此创建你需要的内容。

英文:

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

答案2

得分: 0

这里我写了一个简单的程序,用于解析 JSON。你可以在这个链接中查看:http://play.golang.org/p/51eiswgznR。

你可能还想阅读一下 encoding/json 的文档,可以在这个链接中找到:http://golang.org/pkg/encoding/json/。

英文:

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/

huangapple
  • 本文由 发表于 2013年11月26日 03:37:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/20201712.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定