Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java object to JSON with org.json lib

Tags:

java

org.json

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?

like image 485
Divers Avatar asked Aug 11 '11 12:08

Divers


People also ask

How do I parse a JSON object in Java?

Converting Java object to JSON In it, create an object of the POJO class, set required values to it using the setter methods. Instantiate the ObjectMapper class. Invoke the writeValueAsString() method by passing the above created POJO object. Retrieve and print the obtained JSON.

Can we convert JSONArray to JSONObject?

Core Java bootcamp program with Hands on practiceWe can also add a JSONArray to JSONObject. We need to add a few items to an ArrayList first and pass this list to the put() method of JSONArray class and finally add this array to JSONObject using the put() method.


2 Answers

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();
like image 194
BuffaloBuffalo Avatar answered Sep 27 '22 20:09

BuffaloBuffalo


While JSONObject is the way to go, you need to follow what its JavaDoc says about bean properties:

Construct a JSONObject from an Object using bean getters. It reflects on all of the public methods of the object. For each of the methods with no parameters and a name starting with "get" or "is" followed by an uppercase letter, the method is invoked, and a key and the value returned from the getter method are put into the new JSONObject. The key is formed by removing the "get" or "is" prefix. If the second remaining character is not upper case, then the first character is converted to lower case. For example, if an object has a method named "getName", and if the result of calling object.getName() is "Larry Fine", then the JSONObject will contain "name": "Larry Fine".

Based on the documentation, it will fail in your case because you don't expose those properties via gettings and setters.

like image 27
Mike Thomsen Avatar answered Sep 27 '22 21:09

Mike Thomsen