duanshan2988 2019-06-03 21:19
浏览 343
已采纳

将结构转换为[] json.RawMessage

Trying to convert a struct to []json.RawMessage. My understanding is that json.Marshal() converts it to byte[] as is []json.RawMessage. I cannot however seem to convert between the two. My function expects to receive input as []json.RawMessage.

Have tried several different methods including myIn := json.RawMessage(&myJsonStruct{"string1", "string2"}) and myIn := (*json.RawMessage)(json.Marshal(&myJsonStruct{"string1", "string2"}))

type myJsonStruct struct {
    myString       string  `json:"myString"`
    mySecongString string  `json:"mySecondString"`
}

myIn := json.Marshal(&myJsonStruct{"string1", "string2"})

myFunction(myIn)

myFunction(receivedIn []json.RawMessage) {
    //do work
    return
}
  • 写回答

1条回答 默认 最新

  • douqiao4450 2019-06-03 21:36
    关注

    There are a few things here:

    1. You need to create a new slice of json.RawMessage in order to pass that expected type into your function myFunction as an argument
    2. Store the result of marshaling your custom struct myJsonStruct in a variable myIn (type []byte)
    3. Create a new variable of myInRaw (type json.RawMessage) and append that to the previously created slice of json.RawMessage.

    The above steps will then allow you to pass in the slice of json.RawMessage to your function for further work to be done.

    See example below or working example in the playground:

    package main
    
    import (
        "encoding/json"
    )
    
    type myJsonStruct struct {
        myString       string `json:"myString"`
        mySecongString string `json:"mySecondString"`
    }
    
    func myFunction(receivedIn []json.RawMessage) {
        //do work
        return
    }
    
    func main() {
    
        var rawJSONSlice []json.RawMessage
    
        myIn, err := json.Marshal(
            &myJsonStruct{
                myString:       "string1",
                mySecongString: "string2",
            },
        )
        if err != nil {
            // catch err
        }
    
        myInRaw := json.RawMessage(myIn)
    
        rawJSONSlice = append(rawJSONSlice, myInRaw)
    
        myFunction(rawJSONSlice)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题
  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致