Ethan Sherr Ethan Sherr - 1 year ago 119
Android Question

Java OBJECT to JSONObject

What I am trying to do is create a

method which returns the JSONObject that has some data from the object as a JSONObject!

Here is the method I'd really like to call,

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


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

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

However, eclipse isn't admitting that this specific constructor call is valid, though there's online documentation for it.

How can I get this to work for me?

Answer Source

you have two choices,

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

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

methods for each model object. the implementation of each must use the org.json library to populate the fields of the object, and to build a JSON and from the object's fields, respectively.

b. use GSON or jackson that by design will perform object binding. GSON is simpler, jackson is faster.

really, i did a performance eval of all three, and it went 1. org.json, jackson, and gson, with gson being ~10x slower. it's not really fair to compare org.json however because it doesn't include object binding code.

if you have a simple flat model object with direct mapping to json, they are both brain dead simple. if you want custom mappings or have complex structures, you will need to read the docs and write some custom serialization / deserialization code.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download