Java OBJECT for JSONObject

What I am trying to do is create a method toJSONObject()

that returns a JSONObject with some data from the object as a JSONObject!

Here is the method I would like to call,

public JSONObject(java.lang.Object object, java.lang.String[] names)




- An object that has fields to be used to create a JSONObject.

- an array of strings, the names of the fields to be obtained from the object.

However, eclipse does not admit that this particular constructor call is valid, although there is online documentation there .

How can I get this to work for me?


source to share

4 answers

you have two options:

and. if you want to stick with the standard libraries org.gson you can write your own

public static MyObject fromJson(String json)
public String toJson()


for each model object. each should use the org.json library to populate object fields and to generate JSON and from object fields, respectively.

b. use GSON or jackson which by design will do the object binding. GSON is simpler, Jackson is faster.

Actually, I did a performance evaluation of all three and it went 1. org.json, jackson and gson, with gson being 10x slower. it is not very fair to compare org.json, however, since it does not include object binding code.

if you have a simple flat model object directly mapped to json they are both just dead. if you want to customize mappings or have complex structures, you will need to read the docs and write custom serialization / deserialization code.



As suggested earlier, try Jackson . Not only is it faster, but converting POJOs to / from JSON saves you time and additional coding.

GSON is good too, but unfortunately I noticed that you are doing Android development, HTC messed that up for us, so if you decide to use GSON don't forget the jarjar in the library.



To have JSON functionality in java, you must have JSON-lib. JSON-lib also requires the following "JAR" files:



JSON-lib is a Java library for converting beans, collections, maps, Java arrays and XML to JSON and then re-passing them to beans, collections, maps and more.

In this example, we are going to use the JSONObject class to create a JSONObject and then we will print that object value. To use the JSONObject class, we need to import the following "net.sf.json" package. To add items to this object, we used the put () method. Here is a complete example of code:

import net.sf.json.JSONObject;

public class FirstJSONJava
        public static void main(String args[]) {
        JSONObject object=new JSONObject();
        object.put("name","Amit Kumar");
        object.put("Max.Marks",new Integer(100));
        object.put("Min.Marks",new Double(40));
        object.put("Scored",new Double(66.67));


To run this example, you need to follow these steps:

Download JSON-lib jar and other supporting Jars Add these jars to your classpath create and save Compile it and execute

Source Code



You can use:

new org.json.JSONObject (




All Articles