dongpo3957 2016-08-30 09:30 采纳率: 0%
浏览 271
已采纳

使用json.RawMessage解组json以进行结构化

I need to unmarshal json object which may have the following formats:-

Format1:

    {
    "contactType": 2,
    "value": "0123456789"
    }

Format2:

    {
    "contactType": "MobileNumber",
    "value": "0123456789"
    }

The structure I'm using for unmarshalling is:-

    type Contact struct {
    ContactType int    `json:"contactType"` 
    Value       string `json:"value"`
    }

But this works only for format 1. I dont want to change the datatype of ContactType but I want to accomodate the 2nd format as well. I heard about json.RawMarshal and tried using it.

    type Contact struct {
        ContactType        int
        Value       string          `json:"value"`
        Type json.RawMessage `json:"contactType"
    }

    type StringContact struct {
    Type string `json:"contactType"`
    }

    type IntContact struct {
    Type int `json:"contactType"`
    } 

This gets the unmarshaling done, but I'm unable to set the ContactType variable which depends on the type of json.RawMessage. How do I model my structure so that this problem gets solved?

  • 写回答

1条回答 默认 最新

  • dongzhuzhou4504 2016-08-30 09:57
    关注

    You will need to do the unmarshalling yourself. There is a very good article that shows how to use the json.RawMessage right and a number of other solutions to this very problem, Like using interfaces, RawMessage, implemention your own unmarshal and decode functions etc.

    You will find the article here: JSON decoding in GO by Attila Oláh Note: Attila has made a few errors on his code examples.

    I taken the liberty to put together (using some of the code from Attila) a working example using RawMessage to delay the unmarshaling so we can do it on our own version of the Decode func.

    Link to GOLANG Playground

    package main
    
    import (
        "fmt"
        "encoding/json"
        "io"
    )
    
    type Record struct {
        AuthorRaw json.RawMessage `json:"author"`
        Title     string          `json:"title"`
        URL       string          `json:"url"`
    
        Author Author
    }
    
    type Author struct {
        ID    uint64 `json:"id"`
        Email string `json:"email"`
    }
    
    func Decode(r io.Reader) (x *Record, err error) {
        x = new(Record)
        if err = json.NewDecoder(r).Decode(x); err != nil {
            return
        }
        if err = json.Unmarshal(x.AuthorRaw, &x.Author); err == nil {
            return
        }
        var s string
        if err = json.Unmarshal(x.AuthorRaw, &s); err == nil {
            x.Author.Email = s
            return
        }
        var n uint64
        if err = json.Unmarshal(x.AuthorRaw, &n); err == nil {
            x.Author.ID = n
        }
        return
    }
    
    func main() {
    
        byt_1 := []byte(`{"author": 2,"title": "some things","url": "https://stackoverflow.com"}`)
    
        byt_2 := []byte(`{"author": "Mad Scientist","title": "some things","url": "https://stackoverflow.com"}`)
    
        var dat Record
    
        if err := json.Unmarshal(byt_1, &dat); err != nil {
                panic(err)
        }
        fmt.Printf("%#s
    ", dat)
    
        if err := json.Unmarshal(byt_2, &dat); err != nil {
                panic(err)
        }
        fmt.Printf("%#s
    ", dat)
    }
    

    Hope this helps.

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

报告相同问题?

悬赏问题

  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题