json: cannot unmarshal object into Go value of type main.Shape
--
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...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscribe@googlegroups.com.
The usual way I've seen to do runtime things in JSON would be to use json.RawMessage. The encoded message would look like `{"type":"circle","value":{"radius":10}}` and the Go struct would be `type Shape struct { Type string `json:"type"`; Value json.RawMessage `json:"value"` }` and you'd unmarshal that, and then switch on the Type field to figure out what concrete type you need to unmarshal the Value into.
On Fri, Sep 27, 2013 at 10:55 AM, Steven Blenkinsop <stev...@gmail.com> wrote:
I think you'd want to represent the values in the interface as `{"circle": {"radius": 10}}`. You'd want to wrap either your Shape or []Shape type in a type implementing json.Marshaler/json.Unmarshaler which converts your Shapes to the Go equivalent of this representation before passing it to json, and then uses reflection to convert the default Go representation of the unmarshalled value to the properly typed value. Doing this would require registering types with a type identifier in advance for use by UnmarshalJSON. You might be able to get json to do more of the work for you by storing your Shape values as json encoded strings within your json, i.e. `{"circle":"{\"radius\": 10}"}`, which would allow you to determine the type of value before unmarshalling it, but I haven't thought on it deeply.
On Friday, September 27, 2013, bsr wrote:
Please find the code here--I am trying to Unmarshal a json string to a struct which contains interface.json: cannot unmarshal object into Go value of type main.ShapeWhat is the best strategy to do this.One way I could think of,1. define another struct, where Shape is interface{} type.2. unmarshal the string into this3. use reflection to check the underlying slice,4. if I could somehow extract `Type` field for each item, may typecast to the correct shape.is there an easy way than accepting Shapes into interface{}, or a better way.Thanks.
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/groups/opt_out.