json - 使用 GoLang 的 API(几乎)RESTFul 变量响应
问题描述
我有一个由于各种原因无法替换的软件,并且有一个看起来像 RESTFul 的 API。
所有 EndPoints 都可以响应一个或多个(数组中的)对象,即使 RESTFul 体系结构说它必须响应一个对象数组,如果它只找到一个对象,它就会返回对象而不被包装在数组中。
GET /customers?country_id=10000
{
"count": 5,
"customers": [
{ "id": 10000, "name": "Customer 10000", "vatnum": "123456789P", "country_id": 10000 },
{ "id": 10001, "name": "Customer 10001", "vatnum": "234567891P", "country_id": 10000 },
{ "id": 10002, "name": "Customer 10002", "vatnum": "345678912P", "country_id": 10000 },
{ "id": 10003, "name": "Customer 10003", "vatnum": "456789123P", "country_id": 10000 },
{ "id": 10004, "name": "Customer 10004", "vatnum": "567891234P", "country_id": 10000 }
]
}
GET /customers?vatnum=123456789P
{
"count": 1,
"customers": {
"id": 10000,
"name": "Customer 10000",
"vatnum": "123456789P",
"country_id": 10000
}
}
我的问题是我正在制作这个 API 的客户端,我不知道在映射/解析 Golang 结构中的服务器响应方面解决这个问题的最佳策略是什么。
解决方案
我在使用新的 api 时经常使用这个工具 https://mholt.github.io/json-to-go/ 如果你复制粘贴你的 json 你可以获得自动化的 struts 即:
type AutoGenerated struct {
Count int `json:"count"`
Customers struct {
ID int `json:"id"`
Name string `json:"name"`
Vatnum string `json:"vatnum"`
CountryID int `json:"country_id"`
} `json:"customers"`
}
这是单个结构,另一个只是这个数组。
我意识到我误读了你的问题。 https://golang.org/pkg/encoding/json/#RawMessage 之前的答案是正确的原始消息是最好的。
推荐阅读
- rust - 为什么 std::rc::Rc 可以调用自己的值的方法?
- oracle - Postgres 到 Oracle 数据迁移,无需第三方软件
- java - 带有viewpager和毕加索的应用程序不断停止
- python - 使用 SQLAlchemy 引擎将 Pandas 数据帧保存到 SQLite3 DB
- c++ - 使用已编译的 gcc 编译我的代码,但找不到某些头文件
- php - json解码变成数组到字符串的转换
- c - 为什么 fscanf 只从文件中读取一个字符串的第一个单词
- c++ - 游戏时间步长上的灯光师:std::chrono implementation
- python - 每n步执行一次while循环
- reactjs - Api 调用从应用程序中给出 204