Skip to content

Instantly share code, notes, and snippets.

@capoferro
Last active January 2, 2016 04:08
Show Gist options
  • Save capoferro/8248164 to your computer and use it in GitHub Desktop.
Save capoferro/8248164 to your computer and use it in GitHub Desktop.

Api call 1

{
  "thing": "val"
}

Api call 2

{
  "something": "val"
}
type Foo struct {
  Thing string
}

How would you handle getting "val" into Thing for both Api calls? In the one case, it's a deeply nested object, so I really really don't want to write my own unmarshalling.

I could just have 2 fields, Thing and Something, but that'll kinda suck. Not sure what good options there are, tho.

@capoferro
Copy link
Author

For now I have a field something that I set Thing equal to after the json unmarshal.

@erikh
Copy link

erikh commented Jan 4, 2014

type Foo struct {
  Thing string `json:thing`
  Something string `json:something`
}

func normalizeJson(f Foo) Foo {
  if f.Something != "" {
    f.Thing = f.Something
  } else {
    f.Something = f.Thing
  }

  return f
}

I like the simple approach, which I guess is obvious from the code above.

@slantview
Copy link

Have to agree with @erikh, except that I don't know why you would want to have two fields that go into one. I just represent objects as mirrors of their JSON equivalent.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment