Both Gson and Jackson are good options for serializing/deserializing JSON data,
simple to use and well documented. Advantages of Gson: Simplicity of toJson/fromJson
in the simple cases. For deserialization, do not need access to the Java entities.
But Gson is the faster at deserializing JSONs in compare to Jackson.
For dealing with big json files , jackson is preferred. GSON is faster but Jackson has more
complete support than GSON - like
Extensive annotation support
If case insensivity is of any importance to you, then use Jackson. Gson does not support case
insensitivity for key names, while jackson does.
______________________________________________
Convert String to json object Using GSON Library :
String string = "abcde";
1.You can convert it to a JavaBean if you want using:
Gson gson = new GsonBuilder().setPrettyPrinting().create(); gson.fromJson(string, JavaBean.class);
More Simpler:
String string = "abcde"; // The String which Need To Be Converted
JsonObject convertedObject = new Gson().fromJson(string, JsonObject.class);
2.Using JsonParser :
JsonParser jsonParser = new JsonParser();
JsonObject jo = (JsonObject)jsonParser.parse(json);
Assert.assertNotNull(jo); Assert.assertTrue(jo.get("Success").getAsString());
To do it in a simpler way, consider below:
JsonObject jsonObject = (new JsonParser()).parse(json).getAsJsonObject();
_______________________________________________
Convert Json to String using Jackson:
The methods writeValueAsString and
writeValueAsBytes of ObjectMapper class generate a JSON from a Java object and
return the generated JSON as a string or as a byte array:
public class Car {
private String color;
private String type; // standard getters setters }
________
Car car = new Car("yellow", "renault");
String carAsString = objectMapper.writeValueAsString(car);