Mulgard Mulgard - 3 months ago 25
Java Question

Create JSONObject from POJO

I created a simple POJO:

public class LoginPojo {
private String login_request = null;
private String email = null;
private String password = null;

public String getLogin_request() {
return login_request;
}

public void setLogin_request(String login_request) {
this.login_request = login_request;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}
}


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?

Answer

Simply use the java Gson API:

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

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

Comments