Create JSONObject from POJO
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.
It is possible to get a (gson) JsonObject from POJO:
JsonElement element = gson.toJsonTree(userNested);
JsonObject object = element.getAsJsonObject();
After that you can take object.entrySet()
and look up all the tree.
It is the only absolutely free way in GSON to set dynamically what fields you want to see.
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"}