Special data format processing such as URL and date-JSON framework Jackson Elaboration Part 2

Jackson is the default JSON data processing framework of Spring Boot, but it does not depend on any Spring library. Some friends think that Jackson can only be used in the Spring framework, but it is not. There is no such restriction. It provides many JSON data processing methods and annotations , as well as functions such as streaming API, tree model, data binding , and complex data type conversion. Although it is simple and easy to use, it is definitely not a small toy. This section introduces you to the basic core usage of Jackson. I will write a series of 5-10 articles for more content. Please continue to pay attention to me.

In this article, I will introduce to you, some special JOSN data format processing-JSON framework Jackson Elaboration Part 2:

  • 1. Read JSON data from URL
  • Two, Unknow Properties assignment failure handling
  • Three, unassigned Java Bean serialization
  • Fourth, date formatting

1. Read JSON data from URL

Jackson can not only deserialize strings into Java POJO objects, but also request remote APIs, obtain JSON response results from remote services, and convert them into Java POJO objects.

@Test
void testURL() throws IOException {

  URL url = new URL("https://jsonplaceholder.typicode.com/posts/1"); //远程服务URL
  ObjectMapper mapper = new ObjectMapper();
  //从URL获取JSON响应数据,并反序列化为java 对象
  PostDTO postDTO = mapper.readValue(url, PostDTO.class); 

  System.out.println(postDTO);

}
  • jsonplaceholder.typicode.com Is a free HTTP testing service website, we can use it for testing
  • The remote service API return result is a JSON string, a post manuscript contains userId, id, title, content attributes
  • PostDTO is a java class defined by ourselves, which also contains userId, id, title, content member variables

The following is the console print output result, and postDTO's toString() method output.

PostDTO(userId=1, id=1, title=sunt aut facere repellat provident occaecati excepturi optio reprehenderit, body=quia et suscipit
suscipit recusandae consequuntur expedita et cum
reprehenderit molestiae ut ut quas totam
nostrum rerum est autem sunt rem eveniet architecto)

Two, Unknow Properties assignment failure handling

Sometimes, the JSON string attributes provided by the client are more than the member variables of the java class defined by our server.

For example, the two classes in the figure above,

  • We first serialize PlayerStar into a JSON string, including the age attribute
  • Then convert the JSON string to PlayerStar2, excluding the age attribute
@Test
void testUnknowProperties() throws IOException {
  ObjectMapper mapper = new ObjectMapper();
  PlayerStar player = PlayerStar.getInstance(); //为PlayerStar 各属性赋值,可以参考本系列文章第一篇

  //将PlayerStar序列化为JSON字符串
  String jsonString = mapper.writeValueAsString(player);
  System.out.println(jsonString);
  //将JSON字符串反序列化为PlayerStar2对象
  PlayerStar2 player2 = mapper.readValue(jsonString, PlayerStar2.class);
  System.out.println(player2);
}

When deserializing, the following exception will be thrown. This is because the attributes contained in the JSON string are redundant with the definition of the Java class (there is one more age, and the setAge method cannot be found when assigning values).

{"age":45,"playerName":"乔丹"}

com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "age" (class com.example.demo.javabase.PlayerStar2), not marked as ignorable (one known property: "playerName"])
 at [Source: (String)"{"age":45,"playerName":"乔丹"}"; line: 1, column: 10] (through reference chain: com.example.demo.javabase.PlayerStar2["age"])

If we want to ignore the age attribute and not accept the undefined member variable data of our java class, we can use the following method, and the UnrecognizedPropertyException will not be thrown.

ObjectMapper mapper = new ObjectMapper();
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

Three, unassigned Java Bean serialization

Sometimes, we know that certain types of data may be empty, and we usually don't assign a value to it. But the client needs this {}JSON object, what should we do?

public class MyEmptyObject {
  private Integer i;  //没有get set方法
}

We can set the disable serialization feature for ObjectMapper: FAIL_ON_EMPTY_BEANS, which means that all attributes of the object are allowed to be unassigned.

@Test
void testEmpty() throws IOException {

  ObjectMapper mapper = new ObjectMapper();
  mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);

  String jsonString = mapper.writeValueAsString(new MyEmptyObject());
  System.out.println(jsonString);

}

Without setting by default, the following exception InvalidDefinitionException will be thrown. After setting the disable serialization feature: FAIL_ON_EMPTY_BEANS, it will be serialized into a {}string.

com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class com.example.demo.jackson.JacksonTest1$MyEmptyObject and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS)

Fourth, date formatting

Date formatting is a common requirement in our JSON serialization and deserialization process

ObjectMapper mapper = new ObjectMapper();
Map temp = new HashMap();
temp.put("now", new Date());
String s = mapper.writeValueAsString(temp);
System.out.println(s);

By default, for dates and related types in java, Jackson's serialization results are as follows

{"now":1600564582571}

If we want to format the date in the JSON serialization and deserialization process, we need to do the following processing

ObjectMapper mapper = new ObjectMapper();
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);  //注意这里
mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));  //注意这里
Map temp = new HashMap();
temp.put("now", new Date());

String s = mapper.writeValueAsString(temp);
System.out.println(s);

The console print output is as follows:

{"now":"2020-09-20"}

Welcome to follow my blog, there are many boutique collections

  • This article is reproduced indicate the source (en must not turn only the text): letters Gebo off .

If you think it is helpful to you, please like and share it for me! Your support is my inexhaustible creative motivation! . In addition, the author has output the following high-quality content recently, and I look forward to your attention.

Guess you like

Origin blog.csdn.net/hanxiaotongtong/article/details/108689953