FAQ
Or perhaps something like: http://play.golang.org/p/9N1hj6BwHn - save a
json.Marshal.
On Tuesday, April 26, 2016 at 8:49:24 AM UTC-5, Nick Craig-Wood wrote:
On 26/04/16 12:02, appro...@codinglife.me <javascript:> wrote:
I used json.RawMessage,and it works,thanks very much! Great
But I don't
understand why this code work,this code is a simplified version
It works because you unmarshal to a `interface {}` then marshal back to
JSON, and then unmarshal that back into `specialRsp{}`.

That is rather inefficient but it does work!
import(
"fmt"
"encoding/json"
)
type commonRsp struct{
A string`json:"a"`
B specialRsp `json:"b"`
}
type middleRsp struct{
A string`json:"a"`
B interface{}`json:"b"`//also a interface{}
}
type specialRsp struct{
A string`json:"a"`
B string`json:"b"`
}
func Test(){


speRsp :=&specialRsp{
A :"Test",
B :"Test",
}
comRsp :=&commonRsp{
A :"Test",
B :*speRsp,
}
midRsp :=&middleRsp{}
data,err :=json.Marshal(comRsp)
data = {"a":"Test","b":{"a":"Test","b":"Test"}}
iferr ==nil{
json.Unmarshal(data,midRsp)
midRsp.B is an interface{} so this will be unmarshalled into
map[string]string

midRsp = &{A:Test B:map[a:Test b:Test]}
data,_ :=json.Marshal(midRsp.B)
data here is now JSON

data = {"a":"Test","b":"Test"}
speRsp2 :=&specialRsp{
}
And now we decode the JSON data back into specialRsp
json.Unmarshal(data,speRsp2)
speRsp = &{A:Test B:Test}
fmt.Println(speRsp2.A)

}else{
fmt.Println("Fail")
}
}
See: http://play.golang.org/p/OAUVlnmKsW

--
Nick Craig-Wood <ni...@craig-wood.com <javascript:>> --
http://www.craig-wood.com/nick
--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Search Discussions

Discussion Posts

Previous

Related Discussions

Discussion Navigation
viewthread | post
posts ‹ prev | 11 of 11 | next ›
Discussion Overview
groupgolang-nuts @
categoriesgo
postedApr 26, '16 at 8:00a
activeApr 26, '16 at 2:08p
posts11
users5
websitegolang.org

People

Translate

site design / logo © 2021 Grokbase