Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create JSONObject from POJO

Tags:

java

json

I created a simple POJO:

public class LoginPojo {     private String login_request = null;     private String email = null;     private String password = null;      // getters, setters } 

After some searching I found this: JSONObject jsonObj = new JSONObject( loginPojo );

But with this I got the error:

The constructor JSONObject(LoginPojo) is undefined 

I found another solution:

JSONObject loginJson = new JSONObject(); loginJson.append(loginPojo); 

But this method does not exist.

So how can I convert my POJO into a JSON?

like image 214
Mulgard Avatar asked Nov 20 '14 10:11

Mulgard


People also ask

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.

How do I write a JSONObject file?

UseJSON. stringify(jsonObject) to convert JSON Object to JSON String. Write the stringified object to file using fs. writeFile() function of Node FS module.


2 Answers

Simply use the java Gson API:

Gson gson = new GsonBuilder().create(); String json = gson.toJson(obj);// obj is your object  

And then you can create a JSONObject from this json String, like this:

JSONObject jsonObj = new JSONObject(json); 

Take a look at Gson user guide and this SIMPLE GSON EXAMPLE for more information.

like image 107
cнŝdk Avatar answered Sep 21 '22 23:09

cнŝdk


Jackson provides JSON parser/JSON generator as foundational building block; and adds a powerful Databinder (JSON<->POJO) and Tree Model as optional add-on blocks. This means that you can read and write JSON either as stream of tokens (Streaming API), as Plain Old Java Objects (POJOs, databind) or as Trees (Tree Model). for more reference

You have to add jackson-core-asl-x.x.x.jar, jackson-mapper-asl-x.x.x.jar libraries to configure Jackson in your project.

Modified Code :

LoginPojo loginPojo = new LoginPojo(); ObjectMapper mapper = new ObjectMapper();  try {     mapper.setVisibility(JsonMethod.FIELD, Visibility.ANY);      // Setting values to POJO     loginPojo.setEmail("[email protected]");     loginPojo.setLogin_request("abc");     loginPojo.setPassword("abc");      // Convert user object to json string     String jsonString = mapper.writeValueAsString(loginPojo);      // Display to console     System.out.println(jsonString);  } catch (JsonGenerationException e){     e.printStackTrace(); } catch (JsonMappingException e){     e.printStackTrace(); } catch (IOException e){     e.printStackTrace(); }  Output :  {"login_request":"abc","email":"[email protected]","password":"abc"} 
like image 32
atish shimpi Avatar answered Sep 22 '22 23:09

atish shimpi