Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android

Srivathsan Chellappan
Srivathsan Chellappan
3,323 Points

Mapping JSON to object

Is there an alternative to map every property of every object manually? Isn't there a library that does that?

1 Answer

Rafael Miranda
Rafael Miranda
17,121 Points

Hi,

I use org.json.JSONObject. Like this...

       public static MyObject getObject(String jsonString){
        MyObject cd = null;
        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject(jsonString);
            cd = getObject(jsonObject);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return cd;
    }

 public static MyObject getObject(JSONObject jsonObject) throws JSONException {
        MyObject cd = new MyObject ();
        cd.setId(jsonObject.getInt("id"));
        cd.setQuantity(new BigDecimal(jsonObject.getDouble("quantity")));
        cd.setValue(new BigDecimal(jsonObject.getDouble("value")));

        return cd;
    }
Srivathsan Chellappan
Srivathsan Chellappan
3,323 Points

Thanks Rafael. I guess i was not very clear with my question. I was trying to find out if we could avoid the method getObject (in the sample you have provided). Instead do something like this MyObject myObj = new MyObject(); JSONObject.getObject(jsonString, myObj); kind of auto populate based on public properties (getters and setters) in the object by taking the key from json string and comparing them against prperties.