doulai2025 2019-02-22 07:02
浏览 151
已采纳

具有错误的json输入结构时,Unmarshall应该返回错误

I have struct A and B. When a JSON string A is unmarshalled to struct A then it is valid, however if the JSON string A is unmarshalled to struct B it is still successful (which should not).

Is there any way to detect that wrong JSON input has been wrongly converted to a wrong struct type?

Please look at the code below: play

package main

import (
    "encoding/json"
    "fmt"
)

type A struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}

type B struct {
    Alamat string `json:"alamat"`
    Umur   int    `json:"umur"`
}

func main() {
    var structA A
    var structAA A

    valA := "{\"name\":\"budi\",\"age\":10}"
    valB := "{\"alamat\":\"jakarta\",\"umur\":120}"

    //correct case
    err := json.Unmarshal([]byte(valA), &structA)
    if err != nil {
        fmt.Println("fail unmarshal")
    }

    fmt.Println(structA.Name)
    fmt.Println(structA.Age)

    //unmarshalled successfully but with wrong json
    err = json.Unmarshal([]byte(valB), &structAA)
    if err != nil {
        fmt.Println("fail unmarshal")
    }

    fmt.Println(structAA.Name)
    fmt.Println(structAA.Age)

}
  • 写回答

1条回答 默认 最新

  • douquanqiao6788 2019-02-22 07:11
    关注

    Referring the docs, json.Unmarshal(data []byte, v interface{}), by default, does not work in the way you suppose:

    By default, object keys which don't have a corresponding struct field are ignored (see Decoder.DisallowUnknownFields for an alternative).

    So, JSON properties alamat and umur in your valB are ignored as they are not matched in struct A and name and age are set to their type default.

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

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器