36

I have this simple JSON string where I want user_id to be converted into string when doing json.Unmarshal:

{"user_id": 344, "user_name": "shiki"}

I have tried this:

type User struct {
  Id       string `json:"user_id,int"`
  Username string `json:"user_name"`
}

func main() {
  input := `{"user_id": 344, "user_name": "shiki"}`
  user := User{}
  err := json.Unmarshal([]byte(input), &user)
  if err != nil {
    panic(err)
  }

  fmt.Println(user)
}

But I just get this error:

panic: json: cannot unmarshal number into Go value of type string

Playground link: http://play.golang.org/p/mAhKYiPDt0

1 Answer 1

73

You can use the type json.Number which is implemented as a string:

type User struct {
        Id       json.Number `json:"user_id"`
        Username string      `json:"user_name"`
}

Then you can simply convert it in any other code:

stringNumber := string(userInstance.Id)

Playground: https://play.golang.org/p/2BTtWKkt8ai

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

9 Comments

True. I am currently going with that option (using just int). I am however asking if there's a way to automatically convert it during decoding. It'll be very convenient.
Sorry - I am yet to write my own decoder (still new to Go). That said, it shouldn't be too hard. Googling custom unmarshal/decoder seems to throw up a few links.
OMG. banging head against wall, table, threw laptop out window I've been searching for why I can't convert a json longitude into float64 for hours (days?) cause the source uses empty "" strings when there was none (bad source). So, it was up to me to make exceptional parsing for it. This was insane. "cannot unmarshal number into string", "cannot unmarshal string into float64", "cannot unmarshal X into XX". There is a "json.Number"?!?! ARgh. IT WORKED! +10000
using json.Number works in sending POST data via http. But inside internal Structs I had to convert 8.0 into "8" is this okay ?
Is there any documentation on the ,Number annotation?
|

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.