0

I am writing golang struct, which are compatible with some json structure. However, those most of the fields are know, there will be few fields following some specific patterns(like "x-{randomName}") in the json definition, which I also want to get deserialized to a certain field as map[string]interface{} as well.

Is there any descent way to achieve it?

4
  • 1
    I would probably unmarshal into a temp map[string]interface{}, and have a method to manually map the fields into your struct. Commented Jan 29, 2016 at 19:36
  • I thought about that already. But that would be error prone and time consuming to do it manually(as its a pretty large json with lots of fields) for all fields as most of them are straight forward fixed fields. Commented Jan 29, 2016 at 19:38
  • You could unmarshal twice, once into the struct to get all the defined fields, and once into a map, then clean up the rest. It's less efficient, but would take care of the manual labor. Maybe you could even just dump the entire map into the struct's map and ignore the extra values that were already deserialized. Commented Jan 29, 2016 at 19:41
  • Interesting idea. Thanks! I am gonna try this Commented Jan 29, 2016 at 21:19

1 Answer 1

1

It's less efficient, but you could unmarshal twice to avoid manually mapping the fields. Once to put all the properly tagged fields into the struct, and then again into a map[string]interface{} to get everything else. If you don't care about the duplicate fields, you don't even need to filter the second map.

You can even do this in an UnmarshalJSONmethod to automatically populate the struct

type S struct {
    A   string `json:"a"`
    B   string `json:"b"`
    All map[string]interface{}
}

func (s *S) UnmarshalJSON(b []byte) error {
    // create a new type to hide the UnmarshalJSON method
    // otherwise we'll recurse indefinitely.
    type ss S

    err := json.Unmarshal(b, (*ss)(s))
    if err != nil {
        return err
    }
    // now unmarshal again into the All map
    err = json.Unmarshal(b, &s.All)
    if err != nil {
        return err
    }

    return nil
}

http://play.golang.org/p/VBVlRjNlHy

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.