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 C#读写EXCEL文件,不同编译
  • ¥15 如何提取csv文件中需要的列,将其整合为一篇完整文档,并进行jieba分词(语言-python)
  • ¥15 MapReduce结果输出到HBase,一直连接不上MySQL
  • ¥15 扩散模型sd.webui使用时报错“Nonetype”
  • ¥15 stm32流水灯+呼吸灯+外部中断按键
  • ¥15 将二维数组,按照假设的规定,如0/1/0 == "4",把对应列位置写成一个字符并打印输出该字符
  • ¥15 NX MCD仿真与博途通讯不了啥情况
  • ¥15 win11家庭中文版安装docker遇到Hyper-V启用失败解决办法整理
  • ¥15 gradio的web端页面格式不对的问题
  • ¥15 求大家看看Nonce如何配置