Парсинг json java jackson

Jackson JsonParser

The Jackson JsonParser class is a low level JSON parser. It is similar to the Java StAX parser for XML, except the JsonParser parses JSON and not XML.

The Jackson JsonParser works at a lower level than the Jackson ObjectMapper. This makes the JsonParser faster than the ObjectMapper , but also more cumbersome to work with.

Creating a JsonParser

In order to create a Jackson JsonParser you first need to create a JsonFactory . The JsonFactory is used to create JsonParser instances. The JsonFactory class contains several createParser() methods, each taking a different JSON source as parameter.

Here is an example of creating a JsonParser that parses JSON from a string:

String carJson = "< \"brand\" : \"Mercedes\", \"doors\" : 5 >"; JsonFactory factory = new JsonFactory(); JsonParser parser = factory.createParser(carJson);

You can also pass a Reader , InputStream , URL , byte array or char array to the createParser() method (actually to one of the other overloaded createParser() versions).

Parsing JSON With the JsonParser

Once you have created a Jackson JsonParser you can use it to parse JSON. The way the JsonParser works is by breaking the JSON up into a sequence of tokens which you can iterate one by one.

Here is a JsonParser example that simply loops through all the tokens and print them out to System.out . This is not a very useful example, but it shows you the tokens the JSON is broken up into, and it also shows you the basics of how to loop through the tokens.

String carJson = "< \"brand\" : \"Mercedes\", \"doors\" : 5 >"; JsonFactory factory = new JsonFactory(); JsonParser parser = factory.createParser(carJson); while(!parser.isClosed()) < JsonToken jsonToken = parser.nextToken(); System.out.println("jsonToken codeBox">START_OBJECT END_OBJECT START_ARRAY END_ARRAY FIELD_NAME VALUE_EMBEDDED_OBJECT VALUE_FALSE VALUE_TRUE VALUE_NULL VALUE_STRING VALUE_NUMBER_INT VALUE_NUMBER_FLOAT

You can use these constants to find out what type of token the current JsonToken is. You do so via the equals() method of these constants. Here is an example:

Источник

Jackson – How to parse JSON

Jackson provide writeValue() and readValue() methods to convert Java objects to / from JSON.

mapper.writeValue – Java Objects to JSON

 ObjectMapper mapper = new ObjectMapper(); // Java object to JSON file mapper.writeValue(new File("c:\\test\\staff.json"), new Staff()); // Java object to JSON string, default compact-print String jsonString = mapper.writeValueAsString(new Staff()); // pretty-print String jsonString2 = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(new Staff()); 

mapper.readValue – JSON to Java Objects

 ObjectMapper mapper = new ObjectMapper(); //JSON file to Java object Staff obj = mapper.readValue(new File("c:\\test\\staff.json"), Staff.class); //JSON URL to Java object Staff obj = mapper.readValue(new URL("http://some-domains/api/staff.json"), Staff.class); //JSON string to Java Object Staff obj = mapper.readValue("", Staff.class); 

P.S Tested with Jackson 2.9.8

1. Download Jackson

Declares jackson-databind , it will pull in jackson-annotations and jackson-core

  com.fasterxml.jackson.core jackson-databind 2.9.8  
 $ mvn dependency:tree \- com.fasterxml.jackson.core:jackson-databind:jar:2.9.8:compile [INFO] +- com.fasterxml.jackson.core:jackson-annotations:jar:2.9.0:compile [INFO] \- com.fasterxml.jackson.core:jackson-core:jar:2.9.8:compile 

2. POJO

A simple Java object, POJO, for testing later.

 public class Staff < private String name; private int age; private String[] position; // Array private Listskills; // List private Map salary; // Map // getters , setters, some boring stuff > 

3. Java Objects to JSON

 package com.mkyong; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.File; import java.io.IOException; import java.math.BigDecimal; import java.util.Arrays; import java.util.HashMap; import java.util.Map; public class JacksonExample1 < public static void main(String[] args) < ObjectMapper mapper = new ObjectMapper(); Staff staff = createStaff(); try < // Java objects to JSON file mapper.writeValue(new File("c:\\test\\staff.json"), staff); // Java objects to JSON string - compact-print String jsonString = mapper.writeValueAsString(staff); System.out.println(jsonString); // Java objects to JSON string - pretty-print String jsonInString2 = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(staff); System.out.println(jsonInString2); >catch (IOException e) < e.printStackTrace(); >> private static Staff createStaff() < Staff staff = new Staff(); staff.setName("mkyong"); staff.setAge(38); staff.setPosition(new String[]); Map salary = new HashMap() >; staff.setSalary(salary); staff.setSkills(Arrays.asList("java", "python", "node", "kotlin")); return staff; > > 

4. JSON to Java Object

 package com.mkyong; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.File; import java.io.IOException; public class JacksonExample2 < public static void main(String[] args) < ObjectMapper mapper = new ObjectMapper(); try < // JSON file to Java object Staff staff = mapper.readValue(new File("c:\\test\\staff.json"), Staff.class); // JSON string to Java object String jsonInString = ""; Staff staff2 = mapper.readValue(jsonInString, Staff.class); // compact print System.out.println(staff2); // pretty print String prettyStaff1 = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(staff2); System.out.println(prettyStaff1); > catch (IOException e) < e.printStackTrace(); >> > 

5. @JsonProperty – JSON Field Naming

5.2 Change the property name with @JsonProperty

Читайте также:  Php проверка корректность ввода

6. @JsonInclude – Ignore null fields

By default, Jackson will include null fields.

6.1 @JsonInclude on class level.

 import com.fasterxml.jackson.annotation.JsonInclude; // ignore null fields , class level @JsonInclude(JsonInclude.Include.NON_NULL) // ignore all null fields public class Staff < private String name; private int age; private String[] position; private Listskills; private Map salary; //. 

6.2 @JsonInclude on fields level.

 import com.fasterxml.jackson.annotation.JsonInclude; public class Staff < private String name; private int age; @JsonInclude(JsonInclude.Include.NON_NULL) //ignore null field on this property only private String[] position; private Listskills; private Map salary; 
 ObjectMapper mapper = new ObjectMapper(); // ignore all null fields globally mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); 

7. @JsonView

7.1 The @JsonView is used to limit fields display for different users. For example:

 package com.mkyong; public class CompanyViews < public static class Normal<>; public static class Manager extends Normal<>; > 

Normal view only displays name and age, Manager view is able to display all.

 import com.fasterxml.jackson.annotation.JsonView; import java.math.BigDecimal; import java.util.Arrays; import java.util.List; import java.util.Map; public class Staff < @JsonView(CompanyViews.Normal.class) private String name; @JsonView(CompanyViews.Normal.class) private int age; @JsonView(CompanyViews.Manager.class) private String[] position; @JsonView(CompanyViews.Manager.class) private Listskills; @JsonView(CompanyViews.Manager.class) private Map salary; 
 package com.mkyong; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import java.io.IOException; import java.math.BigDecimal; import java.util.Arrays; import java.util.HashMap; import java.util.Map; public class JacksonExample < public static void main(String[] args) < ObjectMapper mapper = new ObjectMapper(); Staff staff = createStaff(); try < // to enable pretty print mapper.enable(SerializationFeature.INDENT_OUTPUT); // normal String normalView = mapper .writerWithView(CompanyViews.Normal.class) .writeValueAsString(staff); System.out.format("Normal views\n%s\n", normalView); // manager String managerView = mapper .writerWithView(CompanyViews.Manager.class) .writeValueAsString(staff); System.out.format("Manager views\n%s\n", managerView); >catch (IOException e) < e.printStackTrace(); >> private static Staff createStaff() < Staff staff = new Staff(); staff.setName("mkyong"); staff.setAge(38); staff.setPosition(new String[]); Map salary = new HashMap() >; staff.setSalary(salary); staff.setSkills(Arrays.asList("java", "python", "node", "kotlin")); return staff; > > 
 Normal views < "name" : "mkyong", "age" : 38 >Manager views < "name" : "mkyong", "age" : 38, "position" : [ "Founder", "CTO", "Writer" ], "skills" : [ "java", "python", "node", "kotlin" ], "salary" : < "2018" : 14000, "2012" : 12000, "2010" : 10000 >> 

8. @JsonIgnore and @JsonIgnoreProperties

By default, Jackson includes all the fields, even static or transient fields.

Читайте также:  No java edition title

8.1 @JsonIgnore to ignore fields on field level.

 import com.fasterxml.jackson.annotation.JsonIgnore; public class Staff < private String name; private int age; private String[] position; @JsonIgnore private Listskills; @JsonIgnore private Map salary; 

8.2 @JsonIgnoreProperties to ignore fields on class level.

 import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @JsonIgnoreProperties() public class Staff < private String name; private int age; private String[] position; private Listskills; private Map salary; 

9. FAQs

 String json = "[, ]"; List list = Arrays.asList(mapper.readValue(json, Staff[].class)); // or like this: // List list = mapper.readValue(json, new TypeReference()<>); 
 String json = ""; Map map = mapper.readValue(json, Map.class); // or like this: //Map map = mapper.readValue(json, new TypeReference()<>); map.forEach((k, v) -> System.out.format("Парсинг json java jackson:%s \t[value]:%s\n", k, v)); 
 Парсинг json java jackson:name [value]:mkyong Парсинг json java jackson:age [value]:33 

9.3 What if some complex JSON structure doesn’t map easily to a Java class?
Answer: Try Jackson TreeModel to convert JSON data into JsonNode , so that we can add, update or delete JSON nodes easily.

References

mkyong

Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Источник

Jackson JSON parser Quick Examples

Followings are quick getting started examples of using Jackson API for JSON processing. The examples shows the basic data-binding capabilities of Jackson's ObjectMapper class.

Maven dependency

pom.xml

 com.fasterxml.jackson.core jackson-databind 2.9.2 

Simple Java Object Conversion

ObjectMapper om = new ObjectMapper(); Map map = Map.of("one", 1, "two", 2); String s = om.writeValueAsString(map); System.out.println(s);
ObjectMapper om = new ObjectMapper(); String jsonString = ""; Map map = om.readValue(jsonString, Map.class); System.out.println(map); System.out.println(map.getClass());

class java.util.LinkedHashMap

POJO Conversion

public class MyObject < private int intVal; private String StringVal; private Listlist; . >
MyObject pojo = new MyObject(); pojo.setIntVal(3); pojo.setStringVal("test string"); pojo.setList(List.of("item1", "item2")); ObjectMapper om = new ObjectMapper(); String s = om.writeValueAsString(pojo); System.out.println(s);
String s = ""; ObjectMapper om = new ObjectMapper(); MyObject obj = om.readValue(s, MyObject.class); System.out.println(obj);

Conversion Involving Java Generics

As seen in the first example above, Jackson can handle generics for simple types. Let's try generics of a POJO: To Json:

MyObject pojo = new MyObject(); pojo.setIntVal(3); pojo.setStringVal("test string"); pojo.setList(List.of("item1", "item2")); List list = List.of(pojo); ObjectMapper om = new ObjectMapper(); String s = om.writeValueAsString(list); System.out.println(s);
String s = "[]"; ObjectMapper om = new ObjectMapper(); List list = om.readValue(s, List.class); System.out.println(list.get(0)); System.out.println(list.get(0).getClass());

java.lang.ClassCastException: java.base/java.util.LinkedHashMap cannot be cast to com.logicbig.example.MyObject
at com.logicbig.example.PojoTypeReference.toPojo(PojoTypeReference.java:34)

As seen in above output, Jackson cannot infer the actual type (because of Java type erasure problem) and returns 'list of Map' (LinkedHashMap) instead of 'list of MyObject'. To fix that, we need to indicate actual type by providing Jackson's TypeReference anonymous instance:

String s = "[]"; ObjectMapper om = new ObjectMapper(); List list = om.readValue(s, new TypeReference() < >); System.out.println(list.get(0)); System.out.println(list.get(0).getClass());
MyObject 
class com.logicbig.example.MyObject

Reading Writing files

MyObject myObject = new MyObject(); myObject.setIntVal(3); myObject.setStringVal("test string"); myObject.setList(List.of("item1", "item2")); //create temp file File tempFile = File.createTempFile("jackson-", ".txt"); System.out.println("-- saving to file --"); System.out.println(tempFile); //write myObject as JSON to file ObjectMapper om = new ObjectMapper(); om.writeValue(tempFile, myObject); //reading System.out.println("-- reading as text from file --"); String s = new String(Files.readAllBytes(tempFile.toPath())); System.out.println(s); System.out.println("-- reading as Object from file --"); MyObject myObject2 = om.readValue(tempFile, MyObject.class); System.out.println(myObject2);
-- saving to file --
C:\Users\Joe\AppData\Local\Temp\jackson-3890415751750072504.txt
-- reading as text from file --

-- reading as Object from file --
MyObject

Reading from URL

URL url = new URL("https://jsonplaceholder.typicode.com/posts/1"); ObjectMapper om = new ObjectMapper(); Object o = om.readValue(url, Object.class); System.out.println(o); System.out.println("Read as: "+o.getClass().getName());
suscipit recusandae consequuntur expedita et cum
reprehenderit molestiae ut ut quas totam
nostrum rerum est autem sunt rem eveniet architecto>
Read as: java.util.LinkedHashMap

Example Project

Dependencies and Technologies Used:

  • jackson-databind 2.9.2: General data-binding functionality for Jackson: works on core streaming API.
  • JDK 9
  • Maven 3.3.9

Источник

Оцените статью