Java object for JSON with org.json lib

I have a class as follows:

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

Where Alarm is a class like this:

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

Is there an easy way to convert an instance of class 1 to a JSON object with org.json?

+7
source share
2 answers

I think using the org.json.lib JSONObject (Object) constructor is what you are looking for. It will build a JSONObject from your Java object based on its getters. Then you can use JSONObject # toString to get the actual Json.

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

While JSONObject is a way, you need to keep track of what its JavaDoc says about bean properties:

Create a JSONObject from the object using bean getters. This reflects on all commonly available object methods. For each method without parameters and a name starting with "get" or "is" followed by a capital letter, the method is called, and the key and value returned from the getter method are placed in a new JSONObject. the key is formed by removing the "get" or "is" prefix. If the second remaining character is not uppercase, then the first character is converted to lowercase. For example, if an object has a method named "getName", and if the result of the call to object.getName () is "Larry Fine", then JSONObject will contain "name": "Larry Fine".

Based on the documentation, it will fail in your case because you do not provide these properties through nodes and setters.

+4
source

All Articles