Updated 2 December 2020
Jackson is very popular and efficient java based library to serialize and map java based object to json and vice versa.jackson is quiet fast and is of low memory footprint and is suitable for large object graphs or systems.
Note – Turns out that on Android GSON is faster for small Json strings. This is because Jackson has a longer initialization time. With larger Json strings the longer initialization time is made up by the faster proccessing time. But for shorter Json strings GSON is faster because it initializes faster.
jackson ObjectMapper is simplest way to parse json with jackson.ObjectMapper is the main class of jackson library
Dependency
1 |
implementation 'com.fasterxml.jackson.core:jackson-databind:2.2.3' |
Read object from json String
1 2 3 4 5 6 7 8 |
ObjectMapper objectMapper=new ObjectMapper(); String personJson={\"name\":\"Ashwani\",\"mobile\":\"8383838\"}; try{ Person person=objectMapper.readValue(personJson,Person.Class); Log.d("Name :="+person.name+" \n"+"Mobile= "+person.mobile); } catch (IOException e) { e.printStackTrace(); } |
Jackson contains a set of Java annotations which you can use to modify how Jackson reads and writes JSON to and from Java objects.
Properties should only be included if they are non-null, non-empty, or have non-default values. Here is an example that shows how you can use the @JsonInclude
 annotation:
The @JsonProperty annotation is used to map property names with JSON keys during serialization and deserialization. By default, if you try to serialize a POJO, the generated JSON will have keys mapped to the fields of the POJO. If you want to override this behavior, you can use the @JsonProperty annotation on the fields. It takes a String attribute that specifies the name that should be mapped to the field during serialization.
Person Class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
import com.fasterxml.jackson.annotation.JsonInclude; @JsonInclude(JsonInclude.Include.NON_NULL) class Person { @JsonProperty("name") private String name; @JsonProperty("mobile") private String mobile; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } } |
Read object from json File
1 2 3 |
ObjecMapper mapper=new ObjectMapper(); File file=new File("person.json"); mapper.readValue(file,Person.json); |
Read object from json by url
1 2 3 4 5 |
ObjectMapper mapper = new ObjectMapper(); URL url = new URL("file:person.json"); Person person = mapper.readValue(url, Person.class); |
write object to json
1 2 3 4 5 |
ObjectMapper mapper = new ObjectMapper(); Person person = new Person(); mapper.writeValue(new File("person.json"), person); // write to file String jsonStr = mapper.writeValueAsString(person); |
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.