Languages
[Edit]
EN

Java - convert object to JSON String with Jackson lib

4 points
Created by:
Creg
9210

In this short article, we would like to show how to convert any Java object to JSON, using an external Jackson library.

Quick solution:

// import com.fasterxml.jackson.core.JsonProcessingException;
// import com.fasterxml.jackson.databind.ObjectMapper;

ObjectMapper objectMapper = new ObjectMapper();

User userObject = new User("John", 21);
String userJson = objectMapper.writeValueAsString(userObject);

System.out.println(userJson);  // {"name":"John","age":21}

 

Hint: to know how to attach Jackson *.jar library to your project read this article.

Note: if you want to parse JSON to Object read this article.

Maven repository: https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind

 

Practical example

Full example of how to use Jackson library.

Main.java file content:

package examples;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Main {

    public static void main(String[] arg) throws JsonProcessingException {

        ObjectMapper objectMapper = new ObjectMapper();

        User userObject = new User("John", 21);
        String userJson = objectMapper.writeValueAsString(userObject);

        System.out.println(userJson); // {"name":"John","age":21}
    }
}

Example output:

{"name":"John","age":21}

 

User.java file content:

package examples;

public class User {

    private String name;
    private int age;

    // it is good to add no-arguments constructor too
    public User() {
        // nothing here ...
    }

    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return this.name;
    }

    public int getAge() {
        return this.age;
    }
}

 

See also

  1. Java - Jackson library installation instruction
  2. Java - parse JSON to object with Jackson lib

References

  1. Jackson Core - Maven Repository
  2. Jackson Databind - Maven Repository

Alternative titles

  1. jackson convert string to json dirask
  2. java jackson object to string
  3. Java - serialize object to JSON String using Jackson library
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Java JSON - Jackson lib

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join