1

I am trying to unmarshal a json response from the server into various types, but I am not finding how to do it.

The types which work are :-

type ServerResponse struct {
  Total int
  Data  []User
}

type User struct {
  Name  string
  Age   int
}

and I can successfully unmarshal the json and receive the expected User type.

What I want to do is handle various server responses and convert after the fact. eg.

type ServerResponse struct {
  Total int
  Data  []ServerItem
}

type User struct {
  ServerItem
  Name  string
  Age   int
}

type Book struct {
  ServerItem
  Name      string
  Author    string
}

Then use either User(response.Data) or response.Data.(User) to make it a concrete type so that later functions type check correctly.

Please could anyone let me know where to start looking to solve this issue.

1
  • 1
    Could you provide an example of JSON response you want to unmarshal / parse? Commented Nov 25, 2013 at 20:10

2 Answers 2

1

I don't think that this can be done easily. Just decode to map[string]interface{} and create your stuff from this.

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

1 Comment

Thanks, @Volker. That was the conclusion I had come to, but I was hoping that I had missed something somewhere.
0

Here I wrote a simple program that parses json http://play.golang.org/p/51eiswgznR.

You may also want to read the encoding/json docs http://golang.org/pkg/encoding/json/

1 Comment

Thanks very much for the example @mawenbao, I'm going to implement something like that for the configuration of my application.

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.