douzong0711 2019-03-03 05:25
浏览 120
已采纳

json Unmarshal如果在标签中构造属性,则将其替换为零

Here's struct of unmarshal target:

type ParsedObjectType struct{
    Value struct{
        E []struct {
            B bool
            C float32 `json:"coefficient"`
            CE float32
            G int `json:"group"`
            P float32 `json:"period"`
            T int `json:"type"`
        }
    }
}

And soucre string looks like this:

{"B":false,"C":2.123,"CE":0,"G":1,"P":1000,"T":0}

After json.Unmarshal([]byte(string), ParsedObjectType) i receive

{
    "B": false,
    "coefficient": 0,
    "CE": 0,
    "group": 0,
    "period": 0,
    "type": 0
}

with zeros instead of source data in properties

  • 写回答

3条回答 默认 最新

  • douchen7555 2019-03-03 09:06
    关注

    As I understand in json you have compact names, but it should not force you to create cryptic names in structures.

    In the code, you should use meaningful names, but in a serialized format you can use synonyms.

    Adapted from your example: playground: https://play.golang.org/p/gbWhV3FfHMr

    package main
    
    import (
        "encoding/json"
        "log"
    )
    
    type ParsedObjectType struct {
        Value struct {
            Items []struct {
                Coefficient float32 `json:"C"`
                Group       int     `json:"G"`
                Period      float32 `json:"P"`
                TypeValue   int     `json:"T"`
            } `json:"E"`
        }
    }
    
    func main() {
    
        str := `{"Value": {
                "E": [
                  {
                    "B": false,
                    "C": 2.123,
                    "CE": 0,
                    "G": 1,
                    "P": 1000,
                    "T": 0
                  }
                ]
              }
            }`
    
        out := &ParsedObjectType{}
        if err := json.Unmarshal([]byte(str), out); err != nil {
            log.Printf("failed unmarshal %s", err)
        }
    
        log.Printf("Constructed: %#v", out)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

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