30

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?

2
  • did you check out jsonSerializer/de-serializer?
    – Vihar
    Commented Nov 20, 2014 at 10:11
  • 4
    Try using GSON library and gson.toJsonTree(yourObject).getAsJsonObject() Commented Nov 20, 2014 at 10:15

9 Answers 9

48

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.

4
  • 11
    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
    Commented Mar 14, 2017 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
    Commented Mar 14, 2017 at 13:07
  • Don't get me wrong: I am not advocating to down vote your answer.
    – Samuel
    Commented Mar 14, 2017 at 16:02
  • @Samuel No it's fine, I was just clarifying, any way your question was evident too.
    – cнŝdk
    Commented Mar 14, 2017 at 16:10
7

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.

1
  • This solution worked for me at gson-2.2.4 version. Commented Oct 22, 2018 at 13:35
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("[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"}
4
JSONObject input = new JSONObject(pojo);

This worked with latest version.

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20180130</version>
</dependency>
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);
    }
}
2

Simply you can use the below solution:

ObjectMapper mapper = new ObjectMapper();
String str = mapper.writeValueAsString(loginPojo);
JSONObject jsonObject = new JSONObject(str);
0

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

public LoginPojo(){
}
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

0

Simple solution with jackson and these versions of JSONObject which only accepts Map as constructor parameter:

ObjectMapper objectMapper = new ObjectMapper();
JSONObject jsonObject = new JSONObject(objectMapper.convertValue(pojo, Map.class));

Not the answer you're looking for? Browse other questions tagged or ask your own question.