This is documented on mkyong and quoted here:

Jackson is a High-performance JSON processor Java library. In this tutorial, we show you how to use Jackson’s data binding to convert Java object to / from JSON.

For object/json conversion, you need to know following two methods :

//1. Convert Java object to JSON format
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(new File("c:\\user.json"), user);
//2. Convert JSON to Java object
ObjectMapper mapper = new ObjectMapper();
User user = mapper.readValue(new File("c:\\user.json"), User.class);

Note: Both writeValue() and readValue() has many overloaded methods to support different type of inputs and outputs. Make sure check it out.

  1. Jackson Dependency Jackson contains 6 separate jars for different purpose, check here. In this case, you only need “jackson-mapper-asl” to handle the conversion, just declares following dependency in your pom.xml

    <repositories>
        <repository>
            <id>codehaus</id>
            <url>http://repository.codehaus.org/org/codehaus</url>
        </repository>
    </repositories>
    
    <dependencies>
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>1.8.5</version>
        </dependency>
    </dependencies>
    

    For non-maven user, just get the Jackson library here.

  2. POJO

    An user object, initialized with some values. Later use Jackson to convert this object to / from JSON.

    package com.mkyong.core;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class User {
    
        private int age = 29;
        private String name = "mkyong";
        private List<String> messages = new ArrayList<String>() {
            {
                add("msg 1");
                add("msg 2");
                add("msg 3");
            }
        };
    
        //getter and setter methods
    
        @Override
        public String toString() {
            return "User [age=" + age + ", name=" + name + ", " +
                    "messages=" + messages + "]";
        }
    }
    
  3. Java Object to JSON Convert an “user” object into JSON formatted string, and save it into a file “user.json“.

    package com.mkyong.core;
    
    import java.io.File;
    import java.io.IOException;
    import org.codehaus.jackson.JsonGenerationException;
    import org.codehaus.jackson.map.JsonMappingException;
    import org.codehaus.jackson.map.ObjectMapper;
    
    public class JacksonExample {
        public static void main(String[] args) {
    
        User user = new User();
        ObjectMapper mapper = new ObjectMapper();
    
        try {
    
            // convert user object to json string, and save to a file
            mapper.writeValue(new File("c:\\user.json"), user);
    
            // display to console
            System.out.println(mapper.writeValueAsString(user));
    
        } catch (JsonGenerationException e) {
    
            e.printStackTrace();
    
        } catch (JsonMappingException e) {
    
            e.printStackTrace();
    
        } catch (IOException e) {
    
            e.printStackTrace();
    
        }
    
      }
    
    }
    

    Output

    {"age":29,"messages":["msg 1","msg 2","msg 3"],"name":"mkyong"}
    

    Note Above JSON output is hard to read. You can enhance it by enable the pretty print feature.

  4. JSON to Java Object

    Read JSON string from file “user.json“, and convert it back to Java object.

    package com.mkyong.core;
    
    import java.io.File;
    import java.io.IOException;
    import org.codehaus.jackson.JsonGenerationException;
    import org.codehaus.jackson.map.JsonMappingException;
    import org.codehaus.jackson.map.ObjectMapper;
    
    public class JacksonExample {
        public static void main(String[] args) {
    
        ObjectMapper mapper = new ObjectMapper();
    
        try {
    
            // read from file, convert it to user class
            User user = mapper.readValue(new File("c:\\user.json"), User.class);
    
            // display to console
            System.out.println(user);
    
        } catch (JsonGenerationException e) {
    
            e.printStackTrace();
    
        } catch (JsonMappingException e) {
    
            e.printStackTrace();
    
        } catch (IOException e) {
    
            e.printStackTrace();
    
        }
    
      }
    
    }
    

Output

    User [age=29, name=mkyong, messages=[msg 1, msg 2, msg 3]]
Answer from Hazok on Stack Overflow
Top answer
1 of 3
7

This is documented on mkyong and quoted here:

Jackson is a High-performance JSON processor Java library. In this tutorial, we show you how to use Jackson’s data binding to convert Java object to / from JSON.

For object/json conversion, you need to know following two methods :

//1. Convert Java object to JSON format
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(new File("c:\\user.json"), user);
//2. Convert JSON to Java object
ObjectMapper mapper = new ObjectMapper();
User user = mapper.readValue(new File("c:\\user.json"), User.class);

Note: Both writeValue() and readValue() has many overloaded methods to support different type of inputs and outputs. Make sure check it out.

  1. Jackson Dependency Jackson contains 6 separate jars for different purpose, check here. In this case, you only need “jackson-mapper-asl” to handle the conversion, just declares following dependency in your pom.xml

    <repositories>
        <repository>
            <id>codehaus</id>
            <url>http://repository.codehaus.org/org/codehaus</url>
        </repository>
    </repositories>
    
    <dependencies>
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>1.8.5</version>
        </dependency>
    </dependencies>
    

    For non-maven user, just get the Jackson library here.

  2. POJO

    An user object, initialized with some values. Later use Jackson to convert this object to / from JSON.

    package com.mkyong.core;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class User {
    
        private int age = 29;
        private String name = "mkyong";
        private List<String> messages = new ArrayList<String>() {
            {
                add("msg 1");
                add("msg 2");
                add("msg 3");
            }
        };
    
        //getter and setter methods
    
        @Override
        public String toString() {
            return "User [age=" + age + ", name=" + name + ", " +
                    "messages=" + messages + "]";
        }
    }
    
  3. Java Object to JSON Convert an “user” object into JSON formatted string, and save it into a file “user.json“.

    package com.mkyong.core;
    
    import java.io.File;
    import java.io.IOException;
    import org.codehaus.jackson.JsonGenerationException;
    import org.codehaus.jackson.map.JsonMappingException;
    import org.codehaus.jackson.map.ObjectMapper;
    
    public class JacksonExample {
        public static void main(String[] args) {
    
        User user = new User();
        ObjectMapper mapper = new ObjectMapper();
    
        try {
    
            // convert user object to json string, and save to a file
            mapper.writeValue(new File("c:\\user.json"), user);
    
            // display to console
            System.out.println(mapper.writeValueAsString(user));
    
        } catch (JsonGenerationException e) {
    
            e.printStackTrace();
    
        } catch (JsonMappingException e) {
    
            e.printStackTrace();
    
        } catch (IOException e) {
    
            e.printStackTrace();
    
        }
    
      }
    
    }
    

    Output

    {"age":29,"messages":["msg 1","msg 2","msg 3"],"name":"mkyong"}
    

    Note Above JSON output is hard to read. You can enhance it by enable the pretty print feature.

  4. JSON to Java Object

    Read JSON string from file “user.json“, and convert it back to Java object.

    package com.mkyong.core;
    
    import java.io.File;
    import java.io.IOException;
    import org.codehaus.jackson.JsonGenerationException;
    import org.codehaus.jackson.map.JsonMappingException;
    import org.codehaus.jackson.map.ObjectMapper;
    
    public class JacksonExample {
        public static void main(String[] args) {
    
        ObjectMapper mapper = new ObjectMapper();
    
        try {
    
            // read from file, convert it to user class
            User user = mapper.readValue(new File("c:\\user.json"), User.class);
    
            // display to console
            System.out.println(user);
    
        } catch (JsonGenerationException e) {
    
            e.printStackTrace();
    
        } catch (JsonMappingException e) {
    
            e.printStackTrace();
    
        } catch (IOException e) {
    
            e.printStackTrace();
    
        }
    
      }
    
    }
    

Output

    User [age=29, name=mkyong, messages=[msg 1, msg 2, msg 3]]
2 of 3
0

In java we can convert String to json by lot of methods.You can use collection for this purpose HashMap which gives you value in {key:value} pair which could be useful for you and if you are using Spring this can be helpful for you.

   //****************** update The user Info**********************//
        @RequestMapping(value = "/update/{id}",  method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
        public @ResponseBody
        Status updateMsBuddy(@RequestBody MsBuddyInfo msBuddyInfo){

            try{
                if(msBuddyService.updateMsBuddy(msBuddyInfo))
                return new Status(1, "MsBuddyInfo updated Successfully",+msBuddyInfo.getId());
                else
                    return new Status(1, "unable to updated Profile",+msBuddyInfo.getId());
            }
            catch(Exception e){

                return new Status(0,e.toString());
            }
        }
Discussions

java - Convert raw json string in json object with Jackson - Stack Overflow
Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... Json objects can have strings, and those strings can represent another Json object. Ex: ... Assuming the above structure, how do I make jackson deserialize the bar property as a another POJO? More on stackoverflow.com
🌐 stackoverflow.com
JSON string to Java object with Jackson - Stack Overflow
This is probably one of those questions where the title says it all. I am quite fascinated by the ObjectMapper's readValue(file, class) method, found within the Jackson library which reads a JSON ... More on stackoverflow.com
🌐 stackoverflow.com
Converting Java objects to JSON with Jackson - Stack Overflow
Alternatively, you can also use cjson library for converting java object to json string - maven More on stackoverflow.com
🌐 stackoverflow.com
java - Convert JsonObject to Json String with Jackson - Stack Overflow
I am using Jackson and am able to get a JSONObject. I need to be able to convert this JSONObject to its json form. Meaning, the object that is represented by this JSONObject's son string. Somethin... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Baeldung
baeldung.com › home › json › jackson › jackson – marshall string to jsonnode
Jackson - Marshall String to JsonNode | Baeldung
June 28, 2023 - This quick tutorial will show how to use Jackson 2 to convert a JSON String to a JsonNode (com.fasterxml.jackson.databind.JsonNode).
🌐
GeeksforGeeks
geeksforgeeks.org › java › convert-java-object-to-json-string-using-jackson-api
Convert Java Object to Json String using Jackson API - GeeksforGeeks
March 14, 2026 - writeValueAsString() converts a Java object into a JSON string · Jackson automatically maps Java fields to JSON keys using getters · Exception handling is required as serialization may throw checked exceptions · Comment · Basics · Introduction4 ...
🌐
Mkyong
mkyong.com › home › java › how to parse json string with jackson
How to parse JSON string with Jackson | mkyong.com
April 23, 2024 - package com.mkyong.json.jackson; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; public class BasicJsonArrayExample { public static void main(String[] args) { try { // a simple JSON array String json = "[" + "{\"name\": \"mkyong\", \"age\": 20}," + "{\"name\": \"ah pig\", \"age\": 40}," + "{\"name\": \"ag dog\", \"age\": 30}" + "]"; // Jackson main object ObjectMapper mapper = new ObjectMapper(); // read the json strings and convert it into JsonNode JsonNode arrayNode = mapper.readTre
🌐
Attacomsian
attacomsian.com › blog › jackson-convert-json-string-to-json-node
Convert JSON string to JsonNode using Jackson
October 14, 2022 - try { // create object mapper instance ObjectMapper mapper = new ObjectMapper(); // convert JSON file to `JsonNode` JsonNode node = mapper.readTree(Paths.get("user.json").toFile()); // `JsonNode` to JSON string String json = node.toPrettyString(); // print JSON string System.out.println(json); } catch (Exception ex) { ex.printStackTrace(); } The above code will print the following JSON on the console: { "name" : "John Doe", "email" : "john.doe@example.com", "roles" : [ "Member", "Admin" ], "admin" : true, "city" : "New York City", "country" : "United States" } Read the guide Working with Tree Model Nodes in Jackson for more JsonNode examples.
🌐
Quora
quora.com › How-can-I-parse-String-to-JSON-using-Jackson
How to parse String to JSON using Jackson - Quora
Answer (1 of 2): Assuming your json string represents a student as this : [code]{ "name": "Student 1", "age": 19, "scores": [10.0, 11.1, 12.2] } [/code]You can use Jackson’s ObjectMapper as this (assuming your json string is referenced by [code ]studentJson[/code]) : [code]final ObjectMapper...
Find elsewhere
🌐
Mkyong
mkyong.com › home › java › convert java objects to json with jackson
Convert Java Objects to JSON with Jackson | mkyong.com
April 24, 2024 - ObjectMapper mapper = new ObjectMapper(); // JSON file to Java object Person obj = mapper.readValue(new File("person.json"), Person.class); // JSON URL to Java object Person obj = mapper.readValue(new URL("http://some-domains/api/person.json"), Person.class); // JSON string to Java Object String json = "{\"name\": \"mkyong\", \"age\": 20}"; Person obj = mapper.readValue(json, Person.class); This example uses Jackson to convert a Java object Person to a JSON string.
🌐
Educative
educative.io › answers › different-ways-to-convert-a-json-string-to-a-json-object-in-java
Different ways to convert a JSON string to a JSON object in Java
To use the Jackson library, add the Jackson databind dependency from Maven Repository. A node in the JSON is represented in the form of JsonNode in Jackson. Hence, if you convert a string JSON to a JSON object, it would return a JsonNode as the root node...
🌐
Stack Overflow
stackoverflow.com › questions › 43131169 › convert-raw-json-string-in-json-object-with-jackson
java - Convert raw json string in json object with Jackson - Stack Overflow
public void convertToPojo(){ String jsonInString="{ \"foo\" : \"foo\", \"bar\" : \"{\\\"fizz\\\":\\\"baz\\\"}\"}"; ObjectMapper mapper = new ObjectMapper(); FooBarclsObject = mapper.readValue(jsonInString, FooBar.class); } ... Sign up to request ...
🌐
DigitalOcean
digitalocean.com › community › tutorials › jackson-json-java-parser-api-example-tutorial
Jackson JSON Java: Parser API Examples & Tutorial | DigitalOcean
Parse JSON in Java using Jackson library. Complete tutorial with examples for serialization, deserialization, annotations, and advanced JSON processing.
🌐
Java67
java67.com › 2016 › 10 › 3-ways-to-convert-string-to-json-object-in-java.html
3 ways to convert String to JSON object in Java? Examples | Java67
You are saying you are trying to create JSON object, so it looks like you want to convert a Java object into JSON String right? If you are using Gson, you can use toJson() method as shown above. May be posting your code here would help Delete ...
🌐
javathinking
javathinking.com › blog › convert-json-file-to-string-java-jackson
Convert JSON File to String in Java Using Jackson — javathinking.com
It provides a set of APIs to read and write JSON data in various forms, such as converting Java objects to JSON (serialization) and vice versa (deserialization). The main components of Jackson are: ObjectMapper: This is the central class in Jackson. It can be used to read JSON content from various sources (like files, strings) and write JSON content to different destinations.
🌐
Tabnine
tabnine.com › home › convert java object to json
Convert Java object to JSON - Tabnine
July 25, 2024 - The most common way to convert a Java Object to a JSON string is to use an API. The most common APIs for this purpose are Jackson and GSON.
Top answer
1 of 11
714

To convert your object in JSON with Jackson:

import com.fasterxml.jackson.databind.ObjectMapper; 
import com.fasterxml.jackson.databind.ObjectWriter; 

ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json = ow.writeValueAsString(object);
2 of 11
57

I know this is old (and I am new to java), but I ran into the same problem. And the answers were not as clear to me as a newbie... so I thought I would add what I learned.

I used a third-party library to aid in the endeavor: org.codehaus.jackson All of the downloads for this can be found here.

For base JSON functionality, you need to add the following jars to your project's libraries: jackson-mapper-asl and jackson-core-asl

Choose the version your project needs. (Typically you can go with the latest stable build).

Once they are imported in to your project's libraries, add the following import lines to your code:

 import org.codehaus.jackson.JsonGenerationException;
 import org.codehaus.jackson.map.JsonMappingException;
 import com.fasterxml.jackson.databind.ObjectMapper;

With the java object defined and assigned values that you wish to convert to JSON and return as part of a RESTful web service

User u = new User();
u.firstName = "Sample";
u.lastName = "User";
u.email = "sampleU@example.com";

ObjectMapper mapper = new ObjectMapper();
    
try {
    // convert user object to json string and return it 
    return mapper.writeValueAsString(u);
}
catch (JsonGenerationException | JsonMappingException  e) {
    // catch various errors
    e.printStackTrace();
}

The result should looks like this: {"firstName":"Sample","lastName":"User","email":"sampleU@example.com"}

Top answer
1 of 1
16

The code should pass an instance of Type A to the writeValueAsString method not the actual class.

The ObjectMapper will be able to determine the instance's type via reflection, however if you don't pass an instance it cannot determine the field value's to place in the generated JSON.

Also be sure to catch or throw the appropriate exceptions.

public void save() {

try {
        A a = new A();
        ObjectMapper mapper = new ObjectMapper();
        String temp = mapper.writeValueAsString(a);

    } catch (JsonGenerationException e) {
       e.printStackTrace();
    } catch (JsonMappingException e) {
       e.printStackTrace();
    } catch (IOException e) {
       e.printStackTrace();
    }

}

You should also have acessors for the fields on class A and class B. NOTICE I included B in the previous sentence, since Jackson must be able to map all fields on the instance we provide to it.

public A   {
    private List<B> b;
    private int c;

    private B getB(){ return b;}
    private void setB(B b){this.b = b;}
    private int getC(){return c;}
    private void setC(int c){this.c = c;}
}

Here is a complete working example that I have tested.

import java.io.IOException;
import java.util.List;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

public class A {

    private List<B> b;
    private int c;

    public List<B> getB() {
        return b;
    }

    public void setB(List<B> b) {
        this.b = b;
    }

    public int getC() {
        return c;
    }

    public void setC(int c) {
        this.c = c;
    }

    public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {
        A a = new A();
        ObjectMapper mapper = new ObjectMapper();
        String temp = mapper.writeValueAsString(a);
        System.out.println(temp);   
    }
}

class B{


}

If this simple example does not work the jackson-mapper-asl.jar file is most likely not on the build path. Download the file from here and place it somewhere on your local machine.

Next via Eclipse, Right Click on your Project and select properties.

Then select Build Path > Libraries > Add External Jars. Locate the jar and then hit OK.