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

报告相同问题?