我如何解组JSON? [英] How do I Unmarshal JSON?

查看:79
本文介绍了我如何解组JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我仍然在学习Go。我正试图将一个json解组成一个结构体。但是,该结构有一个带有标签的字段。使用反射,我试着看看标签中是否有字符串json。如果是这样,那么解组的json应该简单地以字符串的形式解组到字段中。



示例:

  const data =`{I:3,S:{phone:{sales:2223334444}}}`
type A struct {
I int64
S string`sql:type:json`
}

问题很简单 - 将json中的S解组为一个字符串到结构体A中。

这就是我所走过的距离。但我被困在这里。



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

解决方案

这是做这件事的方法 - 不需要反射。创建一个新类型 RawString 并创建 MarshalJSON UnmarshalJSON 方法为了它。 (游乐场

  // RawString是一个原始编码的JSON对象。 
//它实现了Marshaler和Unmarshaler,可以使用
//延迟JSON解码或预先计算JSON编码。
类型RawString字符串

// MarshalJSON返回* m作为m的JSON编码。
func(m * RawString)MarshalJSON()([] byte,error){
return [] byte(* m),nil
}

// UnmarshalJSON将* m设置为数据副本。
func(m * RawString)UnmarshalJSON(data [] byte)错误{
if m == nil {
return errors.New(RawString:UnmarshalJSON on nil pointer)
}
* m + = RawString(data)
return nil
}

const data =`{i:3,S:{电话:{sales:2223334444}}}`

type A struct {
I int64
S RawString`sql:type:json`

$ b $ func main(){
a:= A {}
err:= json.Unmarshal([] byte(data),& a)
如果错误!= nil {
log.Fatal(Unmarshal failed,err)
}
fmt.Println(完成,a)
}

我修改了 RawMessage 来创建上述内容。


I am still learning Go. I am trying to unmarshal a json into a struct. However, the struct has a field with a tag. Using reflection, I try to see if the tag has the string "json" in it. If it does, then the json to unmarshal should simply be unmarshaled into the field as a string.

Example:

const data = `{"I":3, "S":{"phone": {"sales": "2223334444"}}}`
type A struct {
    I int64
    S string `sql:"type:json"`
}

Problem is simple - unmarshal "S" in the json as a string into the struct A.

This is how far I have come. But I am stuck here.

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

解决方案

This is the go way of doing it - no reflection requred. Create a new type RawString and create MarshalJSON and UnmarshalJSON methods for it. (playground)

// RawString is a raw encoded JSON object.
// It implements Marshaler and Unmarshaler and can
// be used to delay JSON decoding or precompute a JSON encoding.
type RawString string

// MarshalJSON returns *m as the JSON encoding of m.
func (m *RawString) MarshalJSON() ([]byte, error) {
    return []byte(*m), nil
}

// UnmarshalJSON sets *m to a copy of data.
func (m *RawString) UnmarshalJSON(data []byte) error {
    if m == nil {
        return errors.New("RawString: UnmarshalJSON on nil pointer")
    }
    *m += RawString(data)
    return nil
}

const data = `{"i":3, "S":{"phone": {"sales": "2223334444"}}}`

type A struct {
    I int64
    S RawString `sql:"type:json"`
}

func main() {
    a := A{}
    err := json.Unmarshal([]byte(data), &a)
    if err != nil {
        log.Fatal("Unmarshal failed", err)
    }
    fmt.Println("Done", a)
}

I modified the implementation of RawMessage to create the above.

这篇关于我如何解组JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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