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 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大