A slight variation on Richards answer but readTree can take a string so you can simplify it to:

ObjectMapper mapper = new ObjectMapper();
JsonNode actualObj = mapper.readTree("{\"k1\":\"v1\"}");
Answer from slashnick on Stack Overflow
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ convert-java-object-to-json-string-using-jackson-api
Convert Java Object to Json String using Jackson API - GeeksforGeeks
3 weeks ago - 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 ยท Article Tags: Article ...
Discussions

How to convert input string to json string or json object using jackson in java - Stack Overflow
How to convert input string to json string or json object using jackson in java. Thanks in advance More on stackoverflow.com
๐ŸŒ stackoverflow.com
Converting Java objects to JSON with Jackson - Stack Overflow
Well, even the accepted answer does not exactly output what op has asked for. It outputs the JSON string but with " characters escaped. So, although might be a little late, I am answering hopeing it will help people! 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
Convert Java object to JSON without external library
Converting arbitrary objects to JSON isn't particularly easy, especially when there are full solutions already available. Personally, I use Gson, which is pretty easy to use. If the no external libraries is a HARD requirement, then your only choice would be to use reflection to get the names and values of the fields of the object to build the JSON string. You might have recursion problems if there are nested objects that create a circular loop, which complicates things. If you only have to serialize specific classes, then it would probably be easier to essentially hardcode the JSON string generation, and just call the appropriately getters to build the string. Basically, if it's only a few specific classes then you can write your own, if it's any arbitrary object then I highly recommend using a library, but if no libraries then I guess you could try homerolling your own JSON serializer with reflection. More on reddit.com
๐ŸŒ r/javahelp
12
May 1, 2020
๐ŸŒ
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.
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());
            }
        }
๐ŸŒ
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
๐ŸŒ
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).
๐ŸŒ
Javatpoint
javatpoint.com โ€บ parsing-string-to-jsonnode-jackson
Parsing String to JsonNode Jackson - javatpoint
Parsing String to JsonNode Jackson with Jackson Tutorial, Setup Environment, First Application Jackson, ObjectMapper Class, Object Serialization using Jackson, Data Binding, Tree Model etc.
Find elsewhere
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 = "[email protected]";

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":"[email protected]"}

๐ŸŒ
Baeldung
baeldung.com โ€บ home โ€บ json โ€บ jackson โ€บ intro to the jackson objectmapper
Intro to the Jackson ObjectMapper | Baeldung
December 9, 2025 - This tutorial focuses on understanding the Jackson ObjectMapper class and how to serialize Java objects into JSON and deserialize JSON string into Java objects.
๐ŸŒ
Poespas Blog
blog.poespas.me โ€บ posts โ€บ 2024 โ€บ 05 โ€บ 24 โ€บ java-convert-string-to-json
How to Convert a Java String to JSON Format Using Jackson and Gson | Poespas Blog
In this example, we create a Gson instance using the GsonBuilder class. We then use the toJson() method to convert the Java string into JSON. In this article, weโ€™ve demonstrated how to use Jackson and Gson libraries to convert a Java string into JSON format.
๐ŸŒ
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 ...
๐ŸŒ
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
Jackson is a popular and powerful library in Java that is used to deal with JSON data. 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.
๐ŸŒ
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...
๐ŸŒ
Attacomsian
attacomsian.com โ€บ blog โ€บ jackson-convert-json-string-to-json-node
Convert JSON string to JsonNode using Jackson
October 14, 2022 - In this short tutorial, you'll learn how to parse a JSON string to a JsonNode object and vice versa using the Jackson library.
๐ŸŒ
Tabnine
tabnine.com โ€บ home โ€บ convert java object to json
Convert Java object to JSON - Tabnine
July 25, 2024 - Converting a Java Obj to a JSON string is simple using JACKSON or GSON API.
๐ŸŒ
Jenkov
jenkov.com โ€บ tutorials โ€บ java-json โ€บ jackson-objectmapper.html
Jackson ObjectMapper
You can convert a JsonNode to a Java object, using the Jackson ObjectMapper treeToValue() method. This is similar to parsing a JSON string (or other source) into a Java object with the Jackson ObjectMapper.
๐ŸŒ
Kodejava
kodejava.org โ€บ how-to-convert-java-object-to-json-string
How to convert Java object to JSON string? - Learn Java by Examples
Print the json string. package org.kodejava.jackson; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.kodejava.jackson.support.Artist; public class ObjectToJson { public static void main(String[] args) { Artist artist = new Artist(); artist.setId(1L); artist.setName("The Beatles"); ObjectMapper mapper = new ObjectMapper(); try { String json = mapper.writeValueAsString(artist); System.out.println("JSON = " + json); } catch (JsonProcessingException e) { e.printStackTrace(); } } }
๐ŸŒ
javaspring
javaspring.net โ€บ blog โ€บ convert-java-string-to-json
Converting Java String to JSON: A Comprehensive Guide โ€” javaspring.net
Jackson is generally considered to be faster than Gson, especially for large JSON documents. You can also reuse the ObjectMapper in Jackson or the Gson instance in Gson to avoid unnecessary object creation. Converting Java strings to JSON is an essential task in many Java applications.