如何将 JSON 解组为包含 2 个包含相同 JSON 标签名称 ( ) 的字段 (UserName和)的结构?Namename
package main
import (
"encoding/json"
"fmt"
)
type User struct {
UserName string `json:"name,omitempty"`
Name string `json:"name,omitempty"`
}
func main() {
data := []byte(`
{
"name":"kishore"
}
`)
user := &User{}
err := json.Unmarshal(data, &user)
if err != nil {
panic(err)
}
fmt.Printf("value of user : %+v\n", user)
}
Run Code Online (Sandbox Code Playgroud)
实际输出:
value of user : &{UserName: Name:}
预期输出:
value of user : &{UserName:kishore Name:kishore}
如何获取UserName和Name字段填充kishore?
当我查看Json的源代码时,我发现如果 2 个顶级字段具有相同的标签名称,它们就会丢弃。但是代码中的这个注释让我思考是否有一种方法可以标记两者either both tagged or neither tagged
func dominantField(fields []field) (field, bool) {
// The fields are sorted in increasing index-length order, then by presence of tag.
// That means that the first field is the dominant one. We need only check
// for error cases: two fields at top level, either both tagged or neither tagged.
if len(fields) > 1 && len(fields[0].index) == len(fields[1].index) && fields[0].tag == fields[1].tag {
return field{}, false
}
return fields[0], true
}
Run Code Online (Sandbox Code Playgroud)
游乐场链接: https: //play.golang.org/p/TN9IQ8lFR6a
小智 2
这实际上是重复结构标签导致解组器忽略它的情况。根据官方文档 - “3)否则有多个字段,并且所有字段都会被忽略;不会发生错误。”
https://golang.org/pkg/encoding/json/
您可能应该做的是“检查”并查看您的代码是否存在此类问题。
| 归档时间: |
|
| 查看次数: |
6479 次 |
| 最近记录: |