如果对象以空字符串而不是空结构返回,如何解组json对象 [英] how to unmarshal json object if object is returning as empty string instead of empty struct

查看:74
本文介绍了如果对象以空字符串而不是空结构返回,如何解组json对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在以JSON形式接收某些数据,但是如果对象为空,则它不会返回空结构,而是返回空 取而代之的是字符串,并且在解组时会返回错误.

I'm receiving some data as JSON, but if a object is empty, it does not return a empty struct but a empty string instead, and when unmarshaling, it returns an error.

因此,不是使用{"key":{}}的数据是{"key":""}}的数据,即使使用非必需字段也不起作用

So instead of data being {"key":{}} is {"key":""}} , it does not work even using omitempty field

示例: https://play.golang.org/p/N1iuWBxuo1C

type Store struct {
    Title string `json:"title,omitempty"`
    Item  item   `json:"item,omitempty"`
}
type item struct {
    Price float32 `json:"price,omitempty"`
    Kind  string  `json:"kind,omitempty"`
}

func main() {
    var data1 Store
    json1 := []byte(`{"title":"hello world","item":{"price":45.2,"kind":"fruit"}}`)
    if err := json.Unmarshal(json1, &data1); err != nil {
        log.Println("1, err: ", err)
        return
    }
    log.Printf("data1: %+v\n", data1)
    var data2 Store
    json2 := []byte(`{"title":"hello world","item":{}}`)
    if err := json.Unmarshal(json2, &data2); err != nil {
        log.Println("2, err: ", err)
        return
    }
    log.Printf("data2: %+v\n", data2)
    var data3 Store
    json3 := []byte(`{"title":"hello world","item":""}`)
    if err := json.Unmarshal(json3, &data3); err != nil {
        log.Println("3, err: ", err)
        return
    }
    log.Printf("data3: %+v\n", data3)
}

推荐答案

您可以让您的item类型实现 json.Unmarshaler 界面.

You can have your item type implement the json.Unmarshaler interface.

func (i *item) UnmarshalJSON(data []byte) error {
    if string(data) == `""` {
        return nil
    }

    type tmp item
    return json.Unmarshal(data, (*tmp)(i))
}

https://play.golang.org/p/1TrD57XULo9

这篇关于如果对象以空字符串而不是空结构返回,如何解组json对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆