doukenqiong0588 2017-08-16 19:24
浏览 57
已采纳

我怎么知道该字段设置为null?

I want to output an error if the field in json contains a value of null. How can I do it? I have tried "encoding/json". Maybe I need another library.

Code example:

package main

import (
    "encoding/json"
    "fmt"
    "strings"
)

type Item struct {
    Value  *int
}


func main() {
    var jsonBlob = `[
        {},
        {"Value": null},
        {"Value": 0},
        {"Value": 1}
    ]`
    var items []Item

    err := json.NewDecoder(strings.NewReader(jsonBlob)).Decode(&items)
    if err != nil {
        fmt.Println("error:", err)
    }
    for _, a := range items {
        if a.Value != nil {
            fmt.Println(*a.Value)
        } else {
            fmt.Println(a.Value)
        }
    }
}

I got:

<nil>
<nil>
0
1

I want:

<nil>
<error>
0
1

Please help. Many thanks!

  • 写回答

1条回答 默认 最新

  • duanjian5059 2017-08-16 19:29
    关注

    If you want to control how a type is unmarshaled, you can implement json.Unmarshaler

    Since a map allows you to tell the difference between an unset value, and a null value, unmarshaling first into a generic map[string]interface{} will allow you to inspect the values without tokenizing the JSON.

    type Item struct {
        Value *int
    }
    
    
    func (i *Item) UnmarshalJSON(b []byte) error {
        tmp := make(map[string]interface{})
    
        err := json.Unmarshal(b, &tmp)
        if err != nil {
            return err
        }
    
        val, ok := tmp["Value"]
        if ok && val == nil {
            return errors.New("Value cannot be nil")
    
        }
        if !ok {
            return nil
        }
    
        f, ok := val.(float64)
        if !ok {
            return fmt.Errorf("unexpected type %T for Value", val)
        }
    
        n := int(f)
        i.Value = &n
        return nil
    }
    

    https://play.golang.org/p/MNDsQpfEJA

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 Matlab联合CRUISE仿真编译dll文件报错
  • ¥15 脱敏项目合作,ner需求合作
  • ¥15 脱敏项目合作,ner需求合作
  • ¥30 Matlab打开默认名称带有/的光谱数据
  • ¥50 easyExcel模板 动态单元格合并列
  • ¥15 res.rows如何取值使用
  • ¥15 在odoo17开发环境中,怎么实现库存管理系统,或独立模块设计与AGV小车对接?开发方面应如何设计和开发?请详细解释MES或WMS在与AGV小车对接时需完成的设计和开发
  • ¥15 CSP算法实现EEG特征提取,哪一步错了?
  • ¥15 游戏盾如何溯源服务器真实ip?需要30个字。后面的字是凑数的
  • ¥15 vue3前端取消收藏的不会引用collectId