JSON Manipulation in Java
JSON stands for Java Script Object Notation, in which essentially we represent data in name:value pair in a string.
Example of JSON strin is as follows
{ "lastName":"Smith", "suffix":"Jr", "city":"Foster City", "country":"US", "postalCode":"94404", "firstName":"John" }Which represent the Data about a user. JSON is a standard notation to exchange data.
To process Json String , like converting from Json String to Java or vice versa we have
so many different libraries in Java.One of the Most prominent being Jackson,
Bellow are the example or Some Use cases for Handling Json in Java.
Converting JSON String to Java Object Using Jackson
We can use ObjectMapper to convert a JSON String to java Object.
ObjectMapper mapper = new ObjectMapper(); UserInfo userInfoObj = mapper.readValue(JSONStringSrc, UserInfo.class);
Where UserInfo Object is a POJO class with appropriate Jackson Annotations.
If we want to hide or not map some of the properties from JSON string with Java object
we can use @JsonIgnoreProperties annotations to ignore any unmapped fields.
Converting JSON String to Java Map Using Jackson
ObjectMapper mapper = new ObjectMapper(); Map userInfoObj = mapper.readValue(JSONStringSrc, new TypeReference>() {});Converting Java Object to JSON String
Jackson provide a methond writeValueAsString which converts a mapped Object to json string
mapper.writeValueAsString(userInfoObj);
Comments
Post a Comment