25

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?

cнŝdk
  • 28,676
  • 7
  • 47
  • 67
Mulgard
  • 8,305
  • 26
  • 110
  • 205

8 Answers8

46

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.

GokulRaj K.N.
  • 562
  • 5
  • 19
cнŝdk
  • 28,676
  • 7
  • 47
  • 67
  • 10
    The author asked to transform POJO to type JSONObject, not to type (json) String with gson. In a narrow sense, this is not answering the question. – Samuel Mar 14 '17 at 12:52
  • @Samuel It is far so simple to get it. You just need to pass this string to a new `JSONObject` constructor like this: `JSONObject jsonObj = new JSONObject(json);` or using **JSONParser** `.parse()` method. – cнŝdk Mar 14 '17 at 13:07
  • Don't get me wrong: I am not advocating to down vote your answer. – Samuel Mar 14 '17 at 16:02
  • @Samuel No it's fine, I was just clarifying, any way your question was evident too. – cнŝdk Mar 14 '17 at 16:10
5

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("a@a.com");
    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":"a@a.com","password":"abc"}
atish shimpi
  • 4,461
  • 1
  • 28
  • 46
5

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.

Gangnus
  • 22,127
  • 14
  • 79
  • 132
4
JSONObject input = new JSONObject(pojo);

This worked with latest version.

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20180130</version>
</dependency>
Stalin Gino
  • 572
  • 9
  • 28
2

You can also use project lombok with Gson overriding toString function. It automatically includes builders, getters and setters in order to ease the data assignment like this:

User user = User.builder().username("test").password("test").build();

Find below the example class:

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import com.google.gson.Gson;

@Data
@Builder(toBuilder = true)
@AllArgsConstructor
@NoArgsConstructor
public class User {
    /* User name. */
    private String username;
    /* Password. */
    private String password;

    @Override
    public String toString() {
        return new Gson().toJson(this, User.class);
    }

    public static User fromJSON(String json) {
        return new Gson().fromJson(json, User.class);
    }
}
Carlos Cavero
  • 2,604
  • 5
  • 15
  • 31
2

Simply you can use the below solution:

ObjectMapper mapper = new ObjectMapper();
String str = mapper.writeValueAsString(loginPojo);
JSONObject jsonObject = new JSONObject(str);
Belal R
  • 21
  • 4
0

I use jackson in my project, but I think that u need a empty constructor.

public LoginPojo(){
}
Dave
  • 66
  • 4
0

You can use

 <dependency>
   <groupId>com.alibaba</groupId>
   <artifactId>fastjson</artifactId>
   <version>1.2.13</version>
 </dependency>

To create a JSON object:

@Test
public void whenGenerateJson_thanGenerationCorrect() throws ParseException {
    JSONArray jsonArray = new JSONArray();
    for (int i = 0; i < 2; i++) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("AGE", 10);
        jsonObject.put("FULL NAME", "Doe " + i);
        jsonObject.put("DATE OF BIRTH", "2016/12/12 12:12:12");
        jsonArray.add(jsonObject);
    }
    String jsonOutput = jsonArray.toJSONString();
}

Add the annotations to your POJO class like so:

@JSONField(name = "DATE OF BIRTH")
private String dateOfBirth;
etc...

Then you can simply use:

@Test
public void whenJson_thanConvertToObjectCorrect() {
    Person person = new Person(20, "John", "Doe", new Date());
    String jsonObject = JSON.toJSONString(person);
    Person newPerson = JSON.parseObject(jsonObject, Person.class);

    assertEquals(newPerson.getAge(), 0); // if we set serialize to false
    assertEquals(newPerson.getFullName(), listOfPersons.get(0).getFullName());
}

You can find a more complete tutorial on the following site: https://www.baeldung.com/fastjson

Dezso Gabos
  • 1,682
  • 5
  • 17
  • 26