Java object to JSON with org.json lib

Divers picture Divers · Aug 11, 2011 · Viewed 28.9k times · Source

I have class like this:

public class Class1 {
    private String result;
    private String ip;
    private ArrayList<Class2> alarm;
}

Where Alarm its a class like this:

public class Class2 {
    private String bla;
    private String bla1;
}

Is there easy way to convert instance of Class1 to JSON object with org.json?

Answer

BuffaloBuffalo picture BuffaloBuffalo · Aug 11, 2011

I think the utilizing org.json.lib's JSONObject(Object) constructor is what you're looking for. It will construct a JSONObject from your Java Object based on its getters. You can then use JSONObject#toString to get the actual Json produced.

JSONObject jsonObject = new JSONObject(instanceOfClass1);
String myJson = jsonObject.toString();