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 OverflowA 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\"}");
You need to use an ObjectMapper:
ObjectMapper mapper = new ObjectMapper();
JsonFactory factory = mapper.getJsonFactory(); // since 2.1 use mapper.getFactory() instead
JsonParser jp = factory.createJsonParser("{\"k1\":\"v1\"}");
JsonNode actualObj = mapper.readTree(jp);
Further documentation about creating parsers can be found here.
How to convert input string to json string or json object using jackson in java - Stack Overflow
Converting Java objects to JSON with Jackson - Stack Overflow
JSON string to Java object with Jackson - Stack Overflow
Convert Java object to JSON without external library
Videos
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.
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.
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 + "]"; } }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.
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]]
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());
}
}
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);
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]"}
Try this,
You can't create a new string like your doing.
String string = "{\"id\":100,\"firstName\":\"Adam\"}";
Student student = mapper.readValue(string, Student.class);
And instead of handling errors in every mapper.readValue(json, Class) you can write a helper class which has another Generic method.
and use
String jsonString = "{\"id\":100,\"firstName\":\"Adam\"}";
Student student = JSONUtils.convertToObject(jsonString, Student.class);
I'm returning null and fancying printing trace & checking null later on. You can handle error cases on your own way.
public class JSONUtils {
public static String convertToJSON(Object object) {
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json;
try {
json = ow.writeValueAsString(object);
} catch (JsonProcessingException e) {
e.printStackTrace();
return convertToJSON(e);
}
return json;
}
public static <T> T convertToObject(Class<T> clazz, String jsonString) {
try {
ObjectMapper mapper = new ObjectMapper();
return (T) mapper.readValue(jsonString, clazz);
} catch(Exception e) {
e.printStackTrace();
return null;
}
}
}