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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

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