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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里