I have String variable called jsonString
:
{\"phonetype\":\"N95\",\"cat\":\"WP\"}
Now I want to convert it into JSON Object. I
There are various Java JSON serializers and deserializers linked from the JSON home page.
As of this writing, there are these 22:
- JSON-java.
- JSONUtil.
- jsonp.
- Json-lib.
- Stringtree.
- SOJO.
- json-taglib.
- Flexjson.
- Argo.
- jsonij.
- fastjson.
- mjson.
- jjson.
- json-simple.
- json-io.
- google-gson.
- FOSS Nova JSON.
- Corn CONVERTER.
- Apache johnzon.
- Genson.
- cookjson.
- progbase.
...but of course the list can change.
Converting String to Json Object by using org.json.simple.JSONObject
private static JSONObject createJSONObject(String jsonString){
JSONObject jsonObject=new JSONObject();
JSONParser jsonParser=new JSONParser();
if ((jsonString != null) && !(jsonString.isEmpty())) {
try {
jsonObject=(JSONObject) jsonParser.parse(jsonString);
} catch (org.json.simple.parser.ParseException e) {
e.printStackTrace();
}
}
return jsonObject;
}
String to JSON using Jackson
with com.fasterxml.jackson.databind
:
Assuming your json-string represents as this: jsonString = {"phonetype":"N95","cat":"WP"}
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* Simple code exmpl
*/
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree(jsonString);
String phoneType = node.get("phonetype").asText();
String cat = node.get("cat").asText();
NOTE that GSON with deserializing an interface will result in exception like below.
"java.lang.RuntimeException: Unable to invoke no-args constructor for interface XXX. Register an InstanceCreator with Gson for this type may fix this problem."
While deserialize; GSON don't know which object has to be intantiated for that interface.
This is resolved somehow here.
However FlexJSON has this solution inherently. while serialize time it is adding class name as part of json like below.
{
"HTTPStatus": "OK",
"class": "com.XXX.YYY.HTTPViewResponse",
"code": null,
"outputContext": {
"class": "com.XXX.YYY.ZZZ.OutputSuccessContext",
"eligible": true
}
}
So JSON will be cumber some; but you don't need write InstanceCreator
which is required in GSON.
You can use google-gson
. Details:
Object Examples
class BagOfPrimitives {
private int value1 = 1;
private String value2 = "abc";
private transient int value3 = 3;
BagOfPrimitives() {
// no-args constructor
}
}
(Serialization)
BagOfPrimitives obj = new BagOfPrimitives();
Gson gson = new Gson();
String json = gson.toJson(obj);
==> json is {"value1":1,"value2":"abc"}
Note that you can not serialize objects with circular references since that will result in infinite recursion.
(Deserialization)
BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class);
==> obj2 is just like obj
Another example for Gson:
Gson is easy to learn and implement, you need to know is the following two methods:
-> toJson() – convert java object to JSON format
-> fromJson() – convert JSON into java object
import com.google.gson.Gson;
public class TestObjectToJson {
private int data1 = 100;
private String data2 = "hello";
public static void main(String[] args) {
TestObjectToJson obj = new TestObjectToJson();
Gson gson = new Gson();
//convert java object to JSON format
String json = gson.toJson(obj);
System.out.println(json);
}
}
Output
{"data1":100,"data2":"hello"}
Resources:
Google Gson Project Home Page
Gson User Guide
Example
For setting json single object to list ie
"locations":{
}
in to List<Location>
use
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
jackson.mapper-asl-1.9.7.jar