有一个 小 问题上的话题,但他们都不来覆盖我的情况,因此我创建一个新的.
我有以下JSON:
{"foo":{ "bar": "1", "baz": "2" }, "more": "text"}
Run Code Online (Sandbox Code Playgroud)
有没有办法解组嵌套的bar属性并将其直接分配给struct属性而不创建嵌套的struct?
我现在采用的解决方案如下:
type Foo struct {
More String `json:"more"`
Foo struct {
Bar string `json:"bar"`
Baz string `json:"baz"`
} `json:"foo"`
// FooBar string `json:"foo.bar"`
}
Run Code Online (Sandbox Code Playgroud)
这是一个简化版本,请忽略详细程度.如您所见,我希望能够解析并赋值
// FooBar string `json:"foo.bar"`
Run Code Online (Sandbox Code Playgroud)
我见过人们使用地图,但那不是我的情况.我基本上不关心foo(这是一个大对象)的内容,除了一些特定的元素.
在这种情况下,正确的方法是什么?我不是在寻找奇怪的黑客,所以如果这是要走的路,那我很好.
我想在golang中将字符串转换为整数.但我不知道字符串的格式.例如,"10"- > 10,"65.0"- > 65,"xx"- > 0,"11xx" - > 11,"xx11" - > 0
我做了一些搜索并找到了strconv.ParseInt().但它无法处理"65.0".所以我必须检查字符串的格式.
有没有更好的办法?
假设我在服务器上有以下Go结构
type account struct {
Name string
Balance int
}
Run Code Online (Sandbox Code Playgroud)
我想在传入的请求上调用json.Decode来将其解析为一个帐户.
var ac account
err := json.NewDecoder(r.Body).Decode(&ac)
Run Code Online (Sandbox Code Playgroud)
如果客户端发送以下请求:
{
"name": "test@example.com",
"balance": "3"
}
Run Code Online (Sandbox Code Playgroud)
Decode()将返回以下错误:
json: cannot unmarshal string into Go value of type int
Run Code Online (Sandbox Code Playgroud)
现在可以将其解析为"你为Balance发送了一个字符串,但你真的应该发送一个整数",但这很棘手,因为你不知道字段名称.如果请求中有很多字段,那么它也会变得更加棘手 - 您不知道哪个字段无法解析.
在Go中获取传入请求的最佳方法是什么,并为请求中的任意数量的整数字段返回错误消息"Balance必须是字符串"?