How to convert input string to json string or json object using jackson in java.
Thanks in advance
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());
}
}
Very nice tutorial from journaldev Jackson-JSON processing
you can use com.fasterxml.jackson.databind.ObjectMapper
class of jackson API to read or wirte a string formatted json object.
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 :
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
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.
Java Object to JSON Convert an “user” object into JSON formatted string, and save it into a file “user.json“.
Output
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.
Output