Marshal json.RawMessage

Please find the code here http://play.golang.org/p/zdQ14ItNBZ

I save JSON data as RawMessage, but cannot decode it. I need the containing structure to be Marshalled and Unmarshalled, but I would expect you to be able to get the JSON field.

code:

package main import ( "encoding/json" "fmt" ) type Data struct { Name string Id int Json json.RawMessage } type Data2 struct { Name string Id int } func main() { tmp := Data2{"World", 2} b, err := json.Marshal(tmp) if err != nil { fmt.Println("Error %s", err.Error()) } fmt.Println("b %s", string(b)) test := Data{"Hello", 1, b} b2, err := json.Marshal(test) if err != nil { fmt.Println("Error %s", err.Error()) } fmt.Println("b2 %s", string(b2)) var d Data err = json.Unmarshal(b2, &d) if err != nil { fmt.Println("Error %s", err.Error()) } fmt.Println("d.Json %s", string(d.Json)) var tmp2 Data2 err = json.Unmarshal(d.Json, &tmp2) if err != nil { fmt.Println("Error %s", err.Error()) } fmt.Println("Data2 %+v", tmp2) } 

of

 b %s {"Name":"World","Id":2} b2 %s {"Name":"Hello","Id":1,"Json":"eyJOYW1lIjoiV29ybGQiLCJJZCI6Mn0="} d.Json %s "eyJOYW1lIjoiV29ybGQiLCJJZCI6Mn0=" Error %s json: cannot unmarshal string into Go value of type main.Data2 Data2 %+v { 0} 
+6
source share
2 answers

methods on json.RawMessage all accept a pointer receiver, so you cannot use any of them; you do not have a pointer.

This "works" in the sense that it is executing, but it is probably not the strategy you want: http://play.golang.org/p/jYvh8nHata

basically you need it:

 type Data struct { Name string Id int Json *json.RawMessage } 

and then propagate this change through the rest of your program. What ... what are you really trying to do?

+13
source

Jorellis answer is correct for Go versions up to 1.8.

Go 1.8 and newer will correctly handle marshaling both the pointer and non-json.RawMessage pointer.

Fix commit: https://github.com/golang/go/commit/1625da24106b610f89ff7a67a11581df95f8e234

+5
source

Source: https://habr.com/ru/post/955133/


All Articles