Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of json Serialization

2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly shows you the "sample analysis of json serialization", which is easy to understand and clear. I hope it can help you solve your doubts. Let the editor lead you to study and study the "sample analysis of json serialization".

Json serialization (details of javaBean to Json)

When the Java object is converted to json, if there is an attribute value of null in the object, should it be sequenced when the json is serialized? Compare the following json conversion methods

Three common json jar serialization fastjson

The fastjson provided by Alibaba, when converting entity classes with json

A method without the beginning of get will not find the serializer.

-- if there is a method that starts with get, but there is no field behind this get method, there is no serializer [metadata integration project falls into this hole].

Prove that it has something to do with the method that starts with get.

When fastJson converts a java object to json, the fastjson default conversion does not serialize the key corresponding to the null value.

/ / when the field is a basic data type, for example, when the field type is int: private int start;private int limit;//. If I do not have a set value, it will be serialized as "limit": 0, "start": 0

The default is 0, and my goal is that if you don't set the value, they won't appear.

I simply changed their type to Integer. There should be other ways to solve the problem by customizing the serialization behavior, not studying it for the time being.

But what if you want to serialize the key corresponding to null?

Then take a closer look at the input parameters when fastjson converts java objects to json: that is, this method:

JSONObject.toJSONString (Object object, SerializerFeature... Features)

SerializerFeature serialization property of Fastjson:

QuoteFieldNames: whether to use double quotation marks when outputting key. Default is true.

WriteMapNullValue: whether to output fields with a value of null. Default is false.

WriteNullNumberAsZero: if the numeric field is null, the output is 0, not null

If the WriteNullListAsEmpty:List field is null, the output is [], not null

WriteNullStringAsEmpty: if the character type field is null, the output is "" instead of null

If the WriteNullBooleanAsFalse:Boolean field is null, the output is false, not null

Combine the above, SerializerFeature... Features is an array, so we can pass in the parameters we want, such as serializing null. The example is as follows:

Public static void main (String [] args) {AutoPartsSearchRequest request = new AutoPartsSearchRequest (); request.setKeywords ("123"); request.setSortingField (" 234242 "); String str = JSONObject.toJSONString (request, SerializerFeature.WriteMapNullValue); System.out.println (str);} Jackson

Java's open source Jackson class is also related to the method at the beginning of get [ibid.].

By default, jackson serializes the key corresponding to null, that is, public static void main (String [] args) throws JsonGenerationException, JsonMappingException, IOException {AutoPartsSearchRequest request = new AutoPartsSearchRequest (); request.setKeywords ("123"); request.setSortingField (" 234242 "); ObjectMapper mapper = new ObjectMapper (); String str = mapper.writeValueAsString (request); System.out.println (str) will be serialized when converting json. / / output result (not formatted here): {"sortingField": "234242", "partsClassifyId": null, "partsSubClassifyId": null, "sortingDirection": null:.}

By the same token, it's okay not to serialize the null, as follows:

Physically

@ JsonInclude (Include.NON_NULL) / / put the tag on the attribute, if the attribute is NULL, do not participate in serialization / / if placed on top of the class, it will work on all properties of this class / / Include.Include.ALWAYS default / / Include.NON_DEFAULT attribute is default / / Include.NON_EMPTY attribute is null ("") or NULL does not serialize / / Include.NON_NULL attribute is NULL deserialized

On the code

ObjectMapper mapper = new ObjectMapper (); mapper.setSerializationInclusion (Include.NON_NULL); / / set the mapper object through this method, and all serialized objects will be serialized according to the modification rule / / Include.Include.ALWAYS default / / Include.NON_DEFAULT property is default value / / Include.NON_EMPTY property is null ("") or is not serialized for NULL / / Include.NON_NULL property is NULL deserialized

Note: it only works for VO, but Map List does not work. In addition, jackson can filter out the attributes you set, so you can study the source code on your own.

Gson

The Gson provided by Google, and the gson serialization is only related to properties (fields) and has nothing to do with the method that begins with get.

Gson, like fastjson, does not serialize the key corresponding to the null value by default. The specific examples are as follows:

Public static void main (String [] args) throws JsonGenerationException, JsonMappingException, IOException {AutoPartsSearchRequest request = new AutoPartsSearchRequest (); request.setKeywords ("123"); request.setSortingField (" 234242 "); Gson g = new GsonBuilder (). Create (); String str = g.toJson (request); System.out.println (str); / / output result: {" sortingField ":" 234242 "," keywords ":" 123 "}}

To serialize the key corresponding to the null value, simply change the above creation code to the following code:

Gson g = new GsonBuilder (). SerializeNulls (). Create (); handling of json serialization

In the json data processing process, the most helpless is the json serializable problem, encountered more, slowly summed up a little experience.

Let's start with the basics.

As mentioned above.

Json.dumps () is used when encoding dict, list and other python objects into json strings, while json.loads () is used to decode json strings into python objects.

As for other basic knowledge can be seen in the documentation, I will mainly talk about how to solve problems.

Class JSONEncoder (json.JSONEncoder): "" solve the problem that ObjectId and datetime can't serializable "" def default (self, o): if isinstance (o, ObjectId): return str (o) if isinstance (o, datetime): return o.isoformat () if isinstance (o, UUID): return o.hex return json.JSONEncoder.default (self, o)

Directly break up the unconvertible types into a class, especially in the data processing of mongodb, you often encounter the conversion errors of objectid and datetime,uuid, and continue to add if you encounter something else in the future.

ObjectId is to be introduced from bson.

From bson import ObjectId

Datetime will also be introduced and it is possible to encounter the situation of NoneType.

NoneType will be introduced from types

From types import NoneType

UUID will be introduced from uuid

From uuid import UUID

The next step is to call this class in the function you are dealing with.

Let's say we have a python_dict and we want to convert it to json_str.

Json_str= json.dumps (python_dict,cls=JSONEncoder,indent=4)

The parameter cls is our own encapsulated class, and the indent parameter is a number, or it may not be added. The reason for this addition will be mentioned later.

If we want the printed json_str to have an eye-catching format, indent will be very useful, as for the specific number, you can set it to 4 because it is consistent with the indentation of python and looks comfortable.

If you want to display the style of json in the front page.

There are two ways:

Using js at the front end, we convert the data into a standard json string before storing it in the database, which can be called directly on the page.

For example, in flask, you can use tags directly.

{{json_str}}

What is displayed in this way is the standard json style, and the content is clear at a glance.

Add:

There is a more sinister place among them. In fact, by this stage, we have already done what we need to do, so there should be no problem in terms of reason. However, in the process of practice, I found that the Chinese format of the results displayed on the page is still incorrect. It is a unicode code such as'\ upright encoding *\ upright encoding'. Go back to the database and find that the unciode code is stored when the data is saved.

Finally, look at the format of json_str and find that it is indeed the code of unicode, so of course it will not be displayed correctly.

So the last step is to add

Json_str = json_str.encode ('utf-8')

Encode the json string as' utf-8'.

In this way, the problem can be solved perfectly.

The above is all the content of the article "sample Analysis of json Serialization". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report