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?
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.
UseJSON. stringify(jsonObject) to convert JSON Object to JSON String. Write the stringified object to file using fs. writeFile() function of Node FS module.
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.
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"}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With