0

I'm trying to deserialize a generic list using Gson. I'm able to deserialize the following JSON:

[{"updated_at":"2012-03-09T11:13:31Z","id":1,"title":"Moda","position":0,"short_name":"Md"},
{"updated_at":"2012-03-09T11:13:40Z","id":2,"title":"Sissi","position":1,"short_name":"SI"},
{"updated_at":"2012-03-09T11:13:47Z","id":3,"title":"Levis","position":2,"short_name":"LV"},
{"updated_at":"2012-03-09T11:14:03Z","id":4,"title":"Dolce&Gabanna","position":3,"short_name":"DG"}]

with the following code:

T[] array = (T[])java.lang.reflect.Array.newInstance(p_class, 0);
gson.fromJson(content, array.getClass());

But now, I have the following JSON what I can't figure out how to deserialize with gson:

[{"brand":{"updated_at":"2012-03-09T11:13:31Z","id":1,"title":"Moda","position":0,"short_name":"Md"}},
{"brand":{"updated_at":"2012-03-09T11:13:40Z","id":2,"title":"Sissi","position":1,"short_name":"SI"}},
{"brand":{"updated_at":"2012-03-09T11:13:47Z","id":3,"title":"Levis","position":2,"short_name":"LV"}},
{"brand":{"updated_at":"2012-03-09T11:14:03Z","id":4,"title":"Dolce&Gabanna","position":3,"short_name":"DG"}}]

Thanks for your help!

3
  • the strange thing is that using the same technique creates the 4 Brand model but all of their attributes are null Commented Mar 9, 2012 at 14:03
  • What is p_class in your code? Commented Mar 9, 2012 at 14:04
  • p_class is a simple Class object such as: Brand.class Commented Mar 9, 2012 at 14:05

1 Answer 1

4

You need to create a new class which has an object named brand and is a type of p_class. Then use gson on your new class as you did before and it should return you an array of your new class. for example:

class Brand{
    private p_class brand;

    public p_class getBrand(){
        return brand;
    }
}

and for gson:

List<Brand> brands = (List<Brand>) gson.fromJson(content, new TypeToken<List<Brand>>(){}.getType());

another way would be doing with ordinary json objects available in android framework:

    JSONArray ar = new JSONArray(content);
    for(int i=0; i<ar.length(); i++){
        JSONObject obj = ar.getJSONObject(i);

        //here is your desired object
        p_class p = gson.fromJson(obj.getJSONObject("brand").toString(), p_class.class);
    }
Sign up to request clarification or add additional context in comments.

2 Comments

Is there a way that I can create these classes generically and automatically? I need to reserve this code as generic
Your first solution can't be generalized, but your second one can be, so it's definetly a good answer, Thank You!!

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.