dszpyf4859 2015-11-06 14:37
浏览 29
已采纳

去json解组选项[重复]

This question already has an answer here:

Trying to find a simple solution to marshaling/unmashaling into the following struct

type Resource struct {
    Data []ResourceData `json:"data"`
}
type ResourceData struct {
    Id string  `json:"id"`
    Type string  `json:"type"`
    Attributes map[string]interface{} `json:"attributes"`
    Relationships map[string]Resource `json:"relationships"`
}
r := Resource{}
json.Unmarshal(body, &r)

this is great if:

body = `{"data":[{"id":"1","type":"blah"}]}`

However I also need it to respond to:

body = `{"data":{"id":"1","type":"blah"}}` //notice no slice

I could make a separate type

type ResourceSingle struct {
    Data ResourceData `json:"data"`
}

However, that would mean needing to duplicate all the functions I have attached to resource, which is possible. However, i would need to find out which type to unmarshal into before executing it, plus when it comes to the relationships part, each of those could contain data:[]{} or data{}, so that idea isn't going to work.

Alternatively I could use

map[string]*json.RawMessage
//or
type Resource struct {
    Data *json.RawMessage `json:"data"`
}

but still, when in json form how do I know if it is a slice or a node to supply the correct struct to unmarshal into?

My last resort is to umarshal into map[string]interface and use lots of reflect testing .. but this is very long winded.

Ideas?

Kind regards, jJ

</div>
  • 写回答

1条回答 默认 最新

  • dongzouche9108 2015-11-06 15:30
    关注

    There's a number of ways to structure it, but the simplest technique comes down to implementing a json.Unmarshaler, and inspecting the type of the data. You can minimally parse the json bytes, often just the first character, or you can try to unmarshal into each type and return the one that succeeds.

    We'll use the latter technique here, and insert the ResourceData into a slice regardless of the incoming data's format, so we can always operate on it in the same manner:

    type Resource struct {
        Data []ResourceData
    }
    
    func (r *Resource) UnmarshalJSON(b []byte) error {
        // this gives us a temporary location to unmarshal into
        m := struct {
            DataSlice struct {
                Data []ResourceData `json:"data"`
            }
            DataStruct struct {
                Data ResourceData `json:"data"`
            }
        }{}
    
        // try to unmarshal the data with a slice
        err := json.Unmarshal(b, &m.DataSlice)
        if err == nil {
            log.Println("got slice")
            r.Data = m.DataSlice.Data
            return nil
        } else if err, ok := err.(*json.UnmarshalTypeError); !ok {
            // something besides a type error occurred
            return err
        }
    
        // try to unmarshal the data with a struct
        err = json.Unmarshal(b, &m.DataStruct)
        if err != nil {
            return err
        }
        log.Println("got struct")
    
        r.Data = append(r.Data, m.DataStruct.Data)
        return nil
    }
    

    http://play.golang.org/p/YIPeYv4AfT

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

报告相同问题?

悬赏问题

  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题
  • ¥15 谁会P4语言啊,我想请教一下
  • ¥15 哪个tomcat中startup一直一闪而过 找不出问题
  • ¥15 这个怎么改成直流激励源给加热电阻提供5a电流呀
  • ¥50 求解vmware的网络模式问题 别拿AI回答
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳
  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥30 请帮我解决一下下面六个代码