Understand fastjson, recognize this article!

Time:2021-5-13

Hello everyone, I’m a piece of cake, a piece of cake eager to be Cai Bucai in the Internet industry. Soft or hard, praise is soft, white whoring is just!
Ghost ~ remember to give me a third company after watching it!

Understand fastjson, recognize this article!

This article mainly introducesThe use of fastjson

If necessary, please refer to

If it helps, don’t forgetgive the thumbs-up

The official account of WeChat has been opened.A good story of a small dishIf you don’t pay attention, remember to pay attention!

Introduction to JSON

JSON (JavaScript object notation) is a lightweight data exchange format. It makes it easy for people to read and write. At the same time, it is convenient for the machine to analyze and generate. It uses aKey: valueIt is an ideal data exchange language to store and express data in the text format, which is often used in the process of data exchange.

“The era of XML is over, now it’s the era of JSON”. I believe that many people have quietly agreed with this point of view now. Have we seriously thought about why it is nowJSONCan replaceXMLThe status of the government. Let’s take a brief look at two ways of expression:

<?xml version="1.0" encoding="gb2312"?>
<class>
    <stu id="001">
        < name > Yang Guo 
        < sex > male < / sex > male
        <age>20</age>
    </stu>  
    <stu id="002">
        < name > Little Dragon Girl    
        < sex > female
        <age>21</age>
    </stu>
</class>
[
    {
        "id": "001",
        "Name": "Yang Guo",
        "Sex": "male",
        "age": "20"
    },
    {
        "id": "002",
        "Name": "Little Dragon Girl",
        "Sex": "female",
        "age": "21"
    }
]

Both methods are used to describe simple class information. There is not much information, but it can be seen clearlyJSONthanXMLMore concise. The specific differences are as follows:

  • Readability:The readability of JSON and XML is almost the same. One side is simple syntax, the other side is standard tag form, so it is difficult to tell the winner from the loser
  • Scalability:XML is naturally extensible, and so is JSON. So if XML can be extended, then JSON can be extended
  • Coding difficulty:XML has rich coding tools, such as Dom4j, JDOM, etc. JSON also provides many tools. But in the absence of tools, because XML has many structural characters, programming is relatively difficult.
  • Decoding difficulty:The parsing of XML needs to consider the child node and parent node, which is very difficult. However, the parsing difficulty of JSON is almost zero, so it seems that we can understand the data structure

Understanding of JSON

JSON has the following form
  • JSON object

Understand fastjson, recognize this article!

{
    "id": "002",
    "Name": "Little Dragon Girl",
    "Sex": "female",
    "age": "21"
}

This is a simple JSON object. We can observe some syntax of JSON

  1. The data is in curly brackets[]
  2. Data inKey: valueIn the form of pairs (the key is mostly in the form of string, and the value can be string, numeric value, and JSON object)
  3. Every twoKey: valuePairs are separated by commas,, the last key value pair needs to be omitted,

We follow the above3Point features, you can easily build a JSON object

Understand fastjson, recognize this article!

["value1","value2","value3"]

or

[
    {
        "id": "001",
        "Name": "Yang Guo",
        "Sex": "male",
        "age": "20"
    },
    {
        "id": "002",
        "Name": "Little Dragon Girl",
        "Sex": "female",
        "age": "21"
    }
]

Arrays are also represented in a simple way:

  1. From the beginning to the end[]package
  2. The primary key of the data is,separate
  • JSON string

Understand fastjson, recognize this article!

'{"Id": "001", "name": "Yang Guo", "sex": "male", "age": "20"}'

JSON strings are very similar to Java strings.

  1. It has to be done in""perhaps''Package data, support string operation
  2. The data format can beJSON objectIt can beJSON arrayOr the combination of two basic forms

That’s allJSONThe basic form of,JSONIt can be used in various languages, and each language has its own characteristicsJSONHow to realize it. Now let’s get familiar with itJavaIn languageFastJSONThe use of.

FastJSON

FastJSONIt is a JSON parser and generator developed by Alibaba engineers based on Java. It can be used to convert Java objects into their JSON representation, and it can also be used to convert JSON strings into equivalent Java objects.FastJSONCan handle any Java object, including pre-existing objects without source code

Fastjson is very convenient to use. We only need to use it in the Maven projectpomThe following dependencies can be introduced into the file:

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.73</version>
</dependency>

The entry class of fastjson API iscom.alibaba.fastjson.JSON, common serialization operations can be done inJSONClass.

Understand fastjson, recognize this article!

API

We’ve introduced it into the projectFastJSONAnd a user class already exists:

@Data
public class User {
    private int id;

    private String name;

    private String sex;
    
    private int age;
}
toJSONString(Object o)

This method is usually the most common, will beJavaBeanSerialization into JSON text

Understand fastjson, recognize this article!

By passing in an object, we can turn the object into a JSON string. Here we pass in more thanJavaBeanIt can also be oneMap object

Understand fastjson, recognize this article!

Pass in aMap objectWe can also get a JSON string.List objectIt’s also applicable:

Understand fastjson, recognize this article!

The result is a standardJSONArrayString of

iftoJSONString(Object o)The output of is only a monotonous line, which makes you look a little tired, so we can use ittoJSONString(Object o, boolean prettyFormat)To make the output look comfortable:

Understand fastjson, recognize this article!

adoptJSONIts own format makes the output look clearer. It’s really sweet~

I’m tired of using these two kinds when I think about them. Where can I find them? Look here. It’s a piece of cake. It’s reasonable. Let’s introduce ittoJSONStringExtended usage of.

JSON.toJSONString(Object object, SerializerFeature... features)

We can see that there is a parameter in this method SerializerFeature...May feel a little strange, indeed, I am also very strange, let’s take a look at what isSerializerFeatureThrough the source code, we can find thatSerializerFeatureIt turns out to be an enumeration class:

Understand fastjson, recognize this article!

Let’s not faint when we see this picture. Although there are many examples, most of them are ignored@deprecatedNote that these are obsolete. What do we usually use

object describe
SerializerFeature.UseSingleQuotes Use single quotation marks instead of double quotation marks. The default isfalse
SerializerFeature.PrettyFormat Whether the result is formatted or not. The default value isfalse
SerializerFeature.WriteDateUseDateFormat If the time is of data, timestamp type, initialize the time in this format“yyyy-MM-dd HH:mm”
SerializerFeature.WriteMapNullValue Whether to output a field with null value. The default value isfalse
SerializerFeature.WriteClassName Type information is written during serialization. The default value isfalse

Use case:

  • SerializerFeature.UseSingleQuotes

Use single quotation marks instead of double quotation marks. The default isfalse

Understand fastjson, recognize this article!

  • SerializerFeature.PrettyFormat

Whether the result is formatted or not. The default value isfalse

Understand fastjson, recognize this article!

  • SerializerFeature.WriteDateUseDateFormat

If the time is of data, timestamp type, initialize the time in this format“yyyy-MM-dd HH:mm”

Understand fastjson, recognize this article!

In this way, we output the date in a fixed formatyyyy-MM-dd HH:mmSometimes we don’t want to get this format, so what should we do

Understand fastjson, recognize this article!

This method supports custom time format, but the method used istoJSONStringWithDateFormat()Here we need to pay attention not to use the wrong method at that time, but also to talk about the side dishesscumbag ~

  • SerializerFeature.WriteMapNullValue

Whether to output a field with null value. The default value isfalse

What’s the use of this? We should be very clear about the use encouraged in the development specificationJavaBeanPass parameters to minimize passing throughMapPass parameters becauseMapIt’s like a black box. For users, they don’t know which fields exist in it at all. For creators, they probably forget which fields exist in it. To solve this problem,JSONSolutions are also introduced:

Understand fastjson, recognize this article!

In the ordinary waytoJSONString()Method, null value seems to beeat upNow, this is likely to be a development disaster!

  • SerializerFeature.WriteClassName

Type information is written during serialization. The default value isfalse. This method can be used in deserialization. The usage is as follows:

Understand fastjson, recognize this article!

In this way, we can see what type of object we serialize.

These are the abovetoJSONStringDo you have a full harvest~

VX search: a good story of small dishes

More dry goods are worth paying attention to, every article is the taste of first love, nail~

  • parseObject(String text)

It’s aboutserializeThen the corresponding isDeserialization

Deserialization is to convert a string in JSON format into a java bean object.

Understand fastjson, recognize this article!

The usage is very simple, can be a standardJSON stringTurn to aJsonobject object, due toJsonobject classRealizedMap interfaceSo we can go throughget()To get the value.

We already knowMapSo we hope to get oneJavaBeanObject.

Understand fastjson, recognize this article!

Of course, it’s OK! We can get what we want by passing in the object type we want to convertJavaBean

exceptBasic deserializationBesides, there is another wayGeneric deserializationavailable

Understand fastjson, recognize this article!

adoptgeneric paradigmSo we don’t have to pass in oneClass objectAnd get our information directlyJavaBean

FastJSONThere’s another use for serialization, and that’s to do itDeep cloning. Some of my friends who have read my previous articles believe that now they have a certain understanding of software design patternsPrototype modeWhat is involvedDeep cloningandShallow cloning

The implementation of shallow cloning is very simple, we only need to implement itCloneableInterface, and then override itclone()method:

Understand fastjson, recognize this article!

What we see in the resultsGood man cardAll belong toXiao WangYes, this is itShallow cloningThe disadvantages of the system are obvious. We want to achieve thatDeep cloningThere are many ways:

  • Manually assign values to reference properties
  • With the help ofFastJSON
  • useJava streamSerialized object for

There are many ways. Let’s focus on themFastJSONThe implementation method of this method is as follows
Understand fastjson, recognize this article!

adoptFastJSONIn fact, the two objects we get are different, which is convenient to implementDeep cloning

For more information on design patterns, please:

2021 has not learned several kinds of creation mode, create an object!

It’s so simple to enter the “structural model” with pictures and text!

Knock on the blackboard《 Behavioral model

parseArray(String text)

This is a willJSON stringToJSONArrayHow to do it

Understand fastjson, recognize this article!

We can also useGeneric serializationTo achieve the same function:

Understand fastjson, recognize this article!

There’s a hole in this way: we useparseArray()In this method, the second parameter needs to be passed in the object type we want to deserialize, but what we need to pass in here is an array. I don’t know if you have put two identical objects in the arraytypeStrange? That’s right. That’s the way to do it. We’re going to do itListHow many objects are there,Type[]The number in this array should match it, otherwise the following error will be thrown:

Understand fastjson, recognize this article!

But if oneListWhen there are multiple objects of different types in, we can use this method:

Understand fastjson, recognize this article!

toJSONBytes(Object o)

takeJSONObject toByte(byte) array

We usually need to convert the object into byte and then transfer it when we communicate on the network. When we use strings, we can’t help thinking that there is a very convenient one in the stringAPIYou can convert a string to a byte array

String STR = small dish;
byte[] bytes = str.getBytes();

But if we’re going to take oneJavaBeanObject into a byte array, we have to use theByteArrayOutputStreamHelp with streaming:

Understand fastjson, recognize this article!

This way can also be very goodJavaBeanObject to byte array, but the code is a bit too much! andFastJSONIt is also very convenientAPIFor use:

Understand fastjson, recognize this article!

And we’re going to turn byte arrays into objects,FastJSONIt also supports:

Understand fastjson, recognize this article!

fromparseObject()We see another strange parameter in this methodFeature, we can find that this is also an enumeration class by clicking the source code

Understand fastjson, recognize this article!

Looking at so many object instances in the same cloud, we make comments on the more common ones as follows:

object describe
AllowUnQuotedFieldNames Determines whether the parser will allow non double quoted property names
AllowSingleQuotes Determines whether the parser allows single quotes to enclose property names and string values
InternFieldNames Determines whether the attribute names of JSON objects can be normalized by string # intern. If allowed, all attribute names of JSON objects will be intern (); If it is not set, it will not be normalized. By default, this property is open.
AllowISO8601DateFormat If it is set to true, it will be directly converted to a date class when the string conforms to the iso8601 format
AllowArbitraryCommas Multiple commas are allowed. If it is set to true, multiple commas will be skipped directly
UseBigDecimal If it is set to true, the BigDecimal class is used to load the numbers, otherwise double is used
IgnoreNotMatch Ignore mismatch
DisableCircularReferenceDetect Disable circular reference detection
InitStringFieldAsEmpty For strings with no values, the property is set to an empty string
SupportArrayToBean Support array to object
OrderedField Properties remain in the original order
DisableSpecialKeyDetect Disable special character checking
UseObjectArray Using object arrays
writeJSONString(OutputStream os, Object o)

This method writes the object to the output stream

Understand fastjson, recognize this article!

Understand fastjson, recognize this article!

The passed in parameter can also be aWriterParticipants:

Understand fastjson, recognize this article!

That’s what we usually useAPIIn addition, in theFastJSONThere is also a note in@JSONFieldWe should also learn to use them flexibly

@JSONField
Name reshaping

Understand fastjson, recognize this article!

Note:If the property isprivateYes, it must beset()Method, otherwise it cannot be deserialized!

@JSONFieldIt is easy to use and can be configured ingetter()setter()perhapsattribute fieldupper

Understand fastjson, recognize this article!

Test results:

Understand fastjson, recognize this article!

The biggest advantage of this method is that it is used to dock strange documents. Why is it strange? Sometimes we need to call a third-party interface, but the value returned by this interface may not conform to the naming standard, so we need to define an entity class to receive it (map is OK, but it is not standard).

At this time, the attribute name of the entity class we defined must be named according to the returned field name, which is a fatal blow to the obsessive-compulsive disorder program@JSONFieldWe’ll take a brief look at an example. The return field of a license plate information entity is as follows:

{"plateid": 01, "plate": 'min a6666d', "imageurl": ' http://... '}

We can see that all the returned field names do not meet the small hump rule. The entity class we defined can’t do this@JSONFieldIt is written as follows:

Understand fastjson, recognize this article!

Test whether the result can be received successfully:

Understand fastjson, recognize this article!

We can see that we have successfully received the results, and the naming of entity classes also conforms to our specifications, killing two birds with one stone.

Understand fastjson, recognize this article!

DataFormat

We can also use this annotation to format our date as we want

Understand fastjson, recognize this article!

Control serialization

When serializing or deserializing, we can specify that the field is not serialized, which is a bit like thisJava streamIntransientmodification.FastJSONSimilar functions can also be realized in

Understand fastjson, recognize this article!

But the disadvantage of deserialization is that although the value is empty, the property name is still empty~

ordinal

We can use itordinalTo specify the order of the fields

Understand fastjson, recognize this article!

You can see from the resultsattribute fieldAccording to the order we set, the use can be that when we return too many fields to the front end, the useful fields will be prioritized to the front, so that the value can be better, instead of layer by layer searching for the required fields.

Custom serialization

Everything can be customized, serialization is no exception ~ we can use itserializeUsingSpecifies the serialization class of the property

Understand fastjson, recognize this article!

In this way, we aim atageThis property is processed by adding units to the specified field

What this article brings isFastJSONThe use of, I hope to bring you a small partner moderator, a long way to go, dishes with you together~

Understand fastjson, recognize this article!

Today’s you work harder, tomorrow’s you will be able to say less words to ask for help!

I am Xiaocai, a man who studies with you. 💋

The official account of WeChat has been opened.A good story of a small dishIf you don’t pay attention, remember to pay attention!

Every article is the taste of first love~

Recommended Today

Still using go micro service? Come and try go zero, it’s beyond your imagination!

Github https://github.com/tal-tech/go-zero Rapid construction of high parallel development micro service 0. Why is it difficult to do well in micro service? In order to do a good job in micro service, we need to understand and master many knowledge points Basic function level Concurrency Control & current limiting to prevent services from being destroyed by […]