duancong7573 2017-09-22 12:50
浏览 44
已采纳

在Go中拆封时如何识别无效值和未指定的字段?

I would like to know if it's possible to differenciate a void value and an unspecified field value.

Here is an example:

var jsonBlob = []byte(`[
    {"Name": "A", "Description": "Monotremata"},
    {"Name": "B"},
    {"Name": "C", "Description": ""}
]`)

type Category struct {
    Name  string
    Description string
}

var categories []Category
err := json.Unmarshal(jsonBlob, &categories)

if err != nil {
    fmt.Println("error:", err)
}
fmt.Printf("%+v", categories)

Also available here: https://play.golang.org/p/NKObQB5j4O

Output:

[{Name:A Description:Monotremata} {Name:B Description:} {Name:C Description:}]

So in this example is it possible to differentiate the description from the category B from the category C?

I just want to be able to differentiate them to have different behavior in the program.

  • 写回答

1条回答 默认 最新

  • doupan6648 2017-09-22 12:53
    关注

    You can distinguish between empty and missing values if you change your field type to be a pointer. If the value is present in JSON with an empty string value, it will be set to a pointer that points to an empty string. If it is not present in JSON, it will be left nil.

    type Category struct {
        Name        string
        Description *string
    }
    

    Output (try it on the Go Playground):

    [{Name:A Description:0x1050c150} {Name:B Description:<nil>} {Name:C Description:0x1050c158}]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?