你可以通过检查字段是否为null来确定字段是否被设置为null。

huangapple go评论91阅读模式
英文:

How can I know that the field is set to null?

问题

我想要在 JSON 字段包含 null 值时输出一个错误。我该如何做呢?我已经尝试了 "encoding/json" 包,也许我需要另一个库。

代码示例:

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("<error>")
        }
    }
}

我得到的输出是:

<nil>
<nil>
0
1

我想要的输出是:

<nil>
<error>
0
1

请帮忙看看。非常感谢!

英文:

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 (
    &quot;encoding/json&quot;
    &quot;fmt&quot;
    &quot;strings&quot;
)

type Item struct {
    Value  *int
}


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

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

I got:

&lt;nil&gt;
&lt;nil&gt;
0
1

I want:

&lt;nil&gt;
&lt;error&gt;
0
1

Please help. Many thanks!

答案1

得分: 4

如果你想控制类型的反序列化过程,你可以实现json.Unmarshaler接口。

由于映射(map)允许你区分未设置的值和null值,首先将其反序列化为通用的map[string]interface{}类型,可以让你在不对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

英文:

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, &amp;tmp)
	if err != nil {
		return err
	}

	val, ok := tmp[&quot;Value&quot;]
	if ok &amp;&amp; val == nil {
		return errors.New(&quot;Value cannot be nil&quot;)

	}
	if !ok {
		return nil
	}

	f, ok := val.(float64)
	if !ok {
		return fmt.Errorf(&quot;unexpected type %T for Value&quot;, val)
	}

	n := int(f)
	i.Value = &amp;n
	return nil
}

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

huangapple
  • 本文由 发表于 2017年8月17日 03:24:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/45721470.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定