Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a Java Object to a JSONObject?

Tags:

i need to convert a POJO to a JSONObject (org.json.JSONObject)

I know how to convert it to a file:

    ObjectMapper mapper = new ObjectMapper();     try {         mapper.writeValue(new File(file.toString()), registrationData);     } catch (JsonGenerationException e) {         e.printStackTrace();     } catch (JsonMappingException e) {         e.printStackTrace();     } catch (IOException e) {         e.printStackTrace();     } 

But I dont want a file this time.

like image 579
Kaloyan Roussev Avatar asked Jun 20 '14 08:06

Kaloyan Roussev


People also ask

Can we convert object to JSONObject in Java?

The ObjectMapper class of the Jackson API provides methods to convert the Java object to JSON format or object. The ObjectMapper class writeValueAsString() method takes the JSON object as a parameter and returns its respective JSON string.

How do you convert JSON to Java object?

We can convert a JSON to Java Object using the readValue() method of ObjectMapper class, this method deserializes a JSON content from given JSON content String.

How do you convert POJO to JSON?

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.


2 Answers

If we are parsing all model classes of server in GSON format then this is a best way to convert java object to JSONObject.In below code SampleObject is a java object which gets converted to the JSONObject.

SampleObject mSampleObject = new SampleObject(); String jsonInString = new Gson().toJson(mSampleObject); JSONObject mJSONObject = new JSONObject(jsonInString); 
like image 91
Vinod Pattanshetti Avatar answered Oct 01 '22 11:10

Vinod Pattanshetti


If it's not a too complex object, you can do it yourself, without any libraries. Here is an example how:

public class DemoObject {      private int mSomeInt;     private String mSomeString;      public DemoObject(int i, String s) {          mSomeInt = i;         mSomeString = s;     }      //... other stuff      public JSONObject toJSON() {          JSONObject jo = new JSONObject();         jo.put("integer", mSomeInt);         jo.put("string", mSomeString);          return jo;     } } 

In code:

DemoObject demo = new DemoObject(10, "string"); JSONObject jo = demo.toJSON(); 

Of course you can also use Google Gson for more complex stuff and a less cumbersome implementation if you don't mind the extra dependency.

like image 28
Philipp Jahoda Avatar answered Oct 01 '22 11:10

Philipp Jahoda