Mekswoll
Mekswoll

Reputation: 1433

deserializing multiple types with gson

I receive the following JSON response from my http web service

{"status":100,"data":[{"name":"kitchen chair","price":25.99,"description":null}]}

Now I want to be able to deserialize this. I stumbled upon Gson from Google, which at first worked well for some small testcases but I'm having some trouble getting the above string deserialized.

I know the data field only has one item in it, but it could hold more than one which is why all responses have the data field as an array.

I was reading the Gson User Guide and ideally I would like to have a Response object which has two attributes: status and data, but the data field would have to be a List of Map objects which presumably is making it hard for Gson.

I then looked at this which is an example closer to my problem but I still can't quite figure it out. In the example the whole response is an array, whereas my JSON string has one string element and then an array.

How would I best go about deserializing this?

Upvotes: 0

Views: 1514

Answers (1)

Programmer Bruce
Programmer Bruce

Reputation: 66943

It's not clear what exactly was already attempted that appeared to be "hard for Gson".

The latest release of Gson handles this simply. Following is an example.

input.json

{
    "status":100,
    "data":
    [
        {
            "name":"kitchen chair",
            "price":25.99,
            "description":null
        }
    ]
}

Response.java

import java.util.List;
import java.util.Map;

class Response
{
  int status;
  List<Map> data;
}

GsonFoo.java

import java.io.FileReader;

import com.google.gson.Gson;

public class GsonFoo
{
  public static void main(String[] args) throws Exception
  {
    Response response = new Gson().fromJson(new FileReader("input.json"), Response.class);
    System.out.println(new Gson().toJson(response));
  }
}

Output:

{"status":100,"data":[{"name":"kitchen chair","price":25.99}]}

Upvotes: 2

Related Questions