Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java OBJECT to JSONObject

Tags:

java

json

android

What I am trying to do is create a toJSONObject() 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)

Where:

object - An object that has fields that should be used to make a JSONObject.
names - 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?

like image 667
Ethan Sherr Avatar asked Feb 07 '26 02:02

Ethan Sherr


1 Answers

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.

https://sites.google.com/site/gson/gson-user-guide

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.

like image 180
Jeffrey Blattman Avatar answered Feb 09 '26 14:02

Jeffrey Blattman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!