Jackson advanced applications

Transfer: https://www.ibm.com/developerworks/cn/java/jackson-advanced-application/index.html

Formatting (including date format)

Different types of date type, Jackson's approach is different.

  • For the date of type java.util.Calendar, java.util.GregorianCalendar, java.sql.Date, java.util.Date, java.sql.Timestamp, if the specified format, into a long type sequence in the file json data. Obviously, this default format, poor readability, format conversion is necessary. Jackson There are many ways to convert the date format.
  • Notes, please refer to the example "annotation Jackson's use" @ JsonFormat of.
  • ObjectMapper embodiment, a method call ObjectMapper setDateFormat, serialized as a string data type in the specified format.
  • For the date of type java.time.LocalDate, also you need to add code mapper.registerModule (new JavaTimeModule ()), while adding a corresponding jar package dependencies
Listing 1. JSR31 0 configuration information
<dependency> 
<groupId>com.fasterxml.jackson.datatype</groupId> 
<artifactId>jackson-datatype-jsr310</artifactId> 
<version>2.9.1</version> 
</dependency>

For Jackson 2.5 or lower, you need to add code objectMapper.registerModule (new JSR310Module ())

  • For the date of type org.joda.time.DateTime, also you need to add code mapper.registerModule (new JodaModule ()), while adding a corresponding jar package dependencies
Listing 2. joda configuration information
<dependency> 
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-joda</artifactId> 
<version>2.9.1</version> 
</dependency>

Generic deserialized

 

Jackson generics deserialized also provide good support.

  • For List type methods can be called to serialize constructCollectionType may be configured TypeReference serialized.
Listing 3. List generics examples
CollectionType javaType = mapper.getTypeFactory() 
.constructCollectionType(List.class, Person.class); 
List<Person> personList = mapper.readValue(jsonInString, javaType); 
List<Person> personList = mapper.readValue(jsonInString, new
   TypeReference<List<Person>>(){});
Listing 4. Map generics examples
// the second parameter is the key type of the map, the map value is the third parameter type of 
 the MapType the javaType = 
    mapper.getTypeFactory () constructMapType (the HashMap.. Class , String. Class , 
    the Person. Class ); 
 the Map <String, the Person > personMap = mapper.readValue (jsonInString, 
    the javaType); 
 the Map <String, the Person> personMap = mapper.readValue (jsonInString, new new 
    typereference <the Map <String, the Person >> () {});

Properties Visualization

All attributes java object are serialized and deserialized, in other words, not all attributes are visual, the visual properties of the default rules are as follows:

  • If the property modifier is public, the property can be serialized and deserialized.
  • If the property modifier is not public, but its getter and setter methods are public, the property can be serialized and deserialized. Because getter method for serialization, and setter methods for de-serialization.
  • If only public property setter methods, with no public getter methods, the property can only be used for deserialization.

To change the default attribute visualization rules need to call ObjectMapper method setVisibility.

The following example makes a modifier to an attribute name may be protected serialization and deserialization.

Listing 5. Properties Example visualization
mapper.setVisibility (PropertyAccessor.FIELD, Visibility.ANY); 
  public  class the Person { 
 public  int Age; 
  protected String name; 
} 
 the PropertyAccessor supported types are ALL, CREATOR, the FIELD, Getter, IS_GETTER, NONE, SETTER 
 the Visibility supported are A 
    NY, DEFAULT, NON_PRIVATE, NONE, PROTECTED_AND_PUBLIC, PUBLIC_ONLY

Attribute filter

When a Java object is serialized to json, some of the properties to be filtered out, does not appear in the json, Jackson has a variety of implementations.

  • Annotation mode, a single attribute may be filtered or filtered @JsonIgnore more attributes with @JsonIgnoreProperties, examples are as follows:
Listing 6. Examples of filtering a property
@JsonIgnore 
public int getAge() 
@JsonIgnoreProperties(value = { "age","birth_date" }) 
public class Person
  • addMixIn method annotated way @JsonIgnoreProperties.

addMixIn method signature as follows:

public ObjectMapper addMixIn(Class<?> target, Class<?> mixinSource);

The method of action is addMixIn mixinSource annotation interface or class overwrites the target or sub-target type annotations. Set with ixIn

Person peixIn of @JsonIgnoreProperties ( "name") is rewritten, ignoring the final attribute is name, json finally generated as follows:

{"birthDate":"2017/09/13","age":40}

  • SimpleBeanPropertyFilter way. This approach is more flexible than the first two methods, but also more complicated.

@JsonFilter first need to set the class or interface, the second set addMixIn, acting on the @JsonFilter java object, the last call SimpleBeanPropertyFilter serializeAllExcept method or a method override serializeAsField S impleBeanPropertyFilter to filter relevant properties. Examples are as follows:

Listing 7. Example Three filtration properties
// Set Filter class or interface 
 @JsonFilter ( " myFilter " ) 
 public  interface the MyFilter {} 
 // set addMixIn 
mapper.addMixIn (the Person. Class , the MyFilter. Class ); 
 // call to the serializeAllExcept SimpleBeanPropertyFilter method 
 SimpleBeanPropertyFilter newFilter =  
 SimpleBeanPropertyFilter.serializeAllExcept ( " Age " ); 
 // or override serializeAsField SimpleBeanPropertyFilter method of 
 SimpleBeanPropertyFilter newFilter = new new SimpleBeanPropertyFilter () { 
 @Override 
 public  void serializeAsField(Object pojo, JsonGenerator jgen, 
 SerializerProvider provider, PropertyWriter writer) 
 throws Exception { 
 if (!writer.getName().equals("age")) { 
 writer.serializeAsField(pojo, jgen, provider); 
 } 
 } 
 }; 
//设置 FilterProvider 
 FilterProvider filterProvider = new SimpleFilterProvider() 
 .addFilter("myFilter", newFilter); 
 mapper.setFilterProvider(filterProvider).writeValueAsString(person);

Custom serialization and deserialization

When Jackson default serialization and de-serialization of the class can not meet the actual needs, you can customize the new serialization and de-serialization of the class.

  • Custom serialization class. From the class defined sequence requires a direct or indirect inheritance StdSerializer or JsonSerializer, while the need to use JsonGenerator generate json, rewriting method serialize, examples are as follows:
Listing 8
public class CustomSerializer extends StdSerializer<Person> { 
@Override 
public void serialize(Person person, JsonGenerator jgen, 
SerializerProvider provider) throws IOException { 
jgen.writeStartObject(); 
jgen.writeNumberField("age", person.getAge()); 
jgen.writeStringField("name", person.getName()); 
jgen.writeEndObject(); 
} 
}

There are several ways to write JsonGenerator support the generation of complex types json, such writeArray, writeTree like. If you want to create a separate JsonGenerator, by JsonFactory () of createGenerator.

  • Custom deserialization class. Since deserialized class definition needs or directly or indirectly inherits StdDeserializer StdDeserializer, while the need to use JsonParser read json, override method deserialize, examples are as follows:
Listing 9. Custom deserialization

 

public class CustomDeserializer extends StdDeserializer<Person> { 
 @Override 
 public Person deserialize(JsonParser jp, DeserializationContext ctxt) 
 throws IOException, JsonProcessingException { 
 JsonNode node = jp.getCodec().readTree(jp); 
 Person person = new Person(); 
 int age = (Integer) ((IntNode) node.get("age")).numberValue(); 
 String name = node.get("name").asText(); 
 person.setAge(age); 
 person.setName(name); 
return person; 
} 
 }

JsonParser json offers many ways to read the information, such as isClosed (), nextToken (), getValueAsString () and the like. If you want to create a separate JsonParser, by JsonFactory () of createParser.

  • Good define custom serialization class and custom deserialization class, if you want to call them in the program, but also needs to be registered Module ObjectMapper, the example below:
10. The list of registered M odule example
Module1 = SimpleModule new new SimpleModule ( " myModule " ); 
module.addSerializer ( new new The customserializer (the Person. Class )); 
module.addDeserializer (the Person. Class , new new CustomDeserializer ()); 
mapper.registerModule (Module1); 
also by way of annotations added to the attribute, the above method or class java object to call them, 
@JsonSerialize ( the using = the customserializer. class ) 
@JsonDeserialize ( the using = CustomDeserializer. class ) 
 public  class the Person

Process model tree

 

Jackson also provides a model tree (tree model) to generate and parse json. If you want to access or modify some of the properties json, tree model is a good choice. JsonNode tree model consists of nodes. Program often used ObjectNode, ObjectNode inherited JsonNode, examples are as follows:

Listing 10. ObjectNode exemplary creation and analysis json
ObjectMapper mapper = new ObjectMapper(); 
//构建 ObjectNode 
ObjectNode personNode = mapper.createObjectNode(); 
//添加/更改属性 
personNode.put("name","Tom"); 
personNode.put("age",40); 
ObjectNode addressNode = mapper.createObjectNode(); 
addressNode.put("zip","000000"); 
addressNode.put("street","NanJing Road " ); 
 // Set the child node 
personNode. The SET ( " address " , addressNode); 
 // find node path 
JsonNode searchNode = personNode.path ( " Street " ); 
 // delete the property 
((ObjectNode) personNode). Remove ( " address " ); 
 // read JSON 
JsonNode the rootNode = mapper.readTree (personNode.toString ()); 
 // JsonNode converted into a java object 
the Person Person = mapper.treeToValue (personNode, the Person. class ); 
 // java Object converted into JsonNode
JsonNode node = mapper.valueToTree(person);

 

to sum up

Firstly, by comparison with other Java-frame json, it describes the benefits of Jackson, Jackson, and describes the composition of the core module, and the role of each section. Then, by way of example herein to explain the basic usage Jackson, describes ObjectMapper the write and read methods, ObjectMapper configuration information set, and the package jackson-annotations using the annotation. Finally, this paper describes in detail the use of higher-order Jackson, which is the focus of this article. These include higher order date format uses a different type of processing (date of ordinary type, date type JDK 8, Joda date type), and other generic List and Map deserialization, visual management properties, three properties of Jackson filtering, custom serialization and deserialization tree model implementation and use. By systematically explain this article, I believe the reader will have a more profound and comprehensive grasp of Jackson.

 

Guess you like

Origin www.cnblogs.com/guanbin-529/p/11489104.html
Recommended