Search code examples
javaorg.json

Java object to JSON with org.json lib


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?


Solution

  • 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();