json.RawMessage的元帅 [英] Marshal of json.RawMessage
问题描述
请在这里找到代码 http://play.golang.org/p/zdQ14ItNBZ
我将JSON数据保存为RawMessage,但无法将其解码。我需要包含的结构是Marshalled和Unmarshalled,但我希望仍然能够获得JSON字段。
代码:
package main
import(
encoding / json
fmt
)
类型数据结构{
名称字符串
Id int
Json json.RawMessage
}
类型Data2结构{
名称字符串
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,字符串(b))
test:= Data {Hello,1,b}
b2,err:= json。 Marshal(test)
if err!= nil {
fmt.Println(Error%s,err.Error())
}
fmt.Println (b2%s,字符串(b2))
var d数据
err = json.Unmarshal(b2,& d)
if err!= nil {
fmt.Prin tln(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)
}
$ b
out:
b%s {Name:World, Id:2}
b2%s {Name:Hello,Id:1,Json:eyJOYW1lIjoiV29ybGQiLCJJZCI6Mn0 =}
d.Json%seyJOYW1lIjoiV29ybGQiLCJJZCI6Mn0 =
错误%s json:无法将字符串解组为数组main.Data2的Go值
Data2%+ v {0}
json.RawMessage上的方法都采用指针接收器,这就是为什么您无法使用它们中的任何一个;你没有指针。
这个有效的意义在于它的执行,但这可能不是你想要的策略: http://play.golang.org/p/jYvh8nHata
类型数据结构{
名称字符串
Id int
Json * json.RawMessage
}
然后通过剩下的程序。什么......你究竟想要做什么?
Please find the code here http://play.golang.org/p/zdQ14ItNBZ
I am keeping JSON data as RawMessage, but cannot decode it out. I need the containing struct to be Marshalled and Unmarshalled, but I would expect still 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)
}
out:
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}
the methods on json.RawMessage all take a pointer receiver, which is why you're not able to utilize any of them; you don't have a pointer.
This "works" in the sense that it executes, but this is likely not the strategy that you want: http://play.golang.org/p/jYvh8nHata
basically you need this:
type Data struct {
Name string
Id int
Json *json.RawMessage
}
and then propagate that change through the rest of your program. What... what are you actually trying to do?
这篇关于json.RawMessage的元帅的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!