Hello everyone, I am xiao CAI, a desire to do CAI Not CAI xiao CAI in the Internet industry. Soft but just, soft praise, white piao just! Ghost ~ remember to give me a three – even oh!

This article focuses on the use of FastJSON

Refer to it if necessary

If it is helpful, do not forget the Sunday

Wechat public number has been opened, xiao CAI Liang, did not pay attention to the students remember to pay attention to oh!

JSON is introduced

JSON(JavaScript Object Notation) is a lightweight data interchange format. It makes it easy to read and write. It also facilitates machine parsing and generation. It uses a text format of “key: value” pair to store and represent data, which is often used in the process of data exchange. It is an ideal data exchange language.

“The age of XML is over. It’s the age of JSON.” I’m sure a lot of people now quietly agree, so have we really thought about why JSON is taking XML’s place now? Let’s look briefly at the two representations:


      
<class>
    <stu id="001">
        <name>Yang2 guo4</name> 
        <sex>male</sex>
        <age>20</age>
    </stu>  
    <stu id="002">
        <name>Little dragon female</name>    
        <sex>female</sex>
        <age>21</age>
    </stu>
</class>
Copy the code
[{"id": "001"."name": "Yang guo"."sex": "Male"."age": "20"
    },
    {
        "id": "002"."name": "Little Dragon Lady"."sex": "Female"."age": "21"}]Copy the code

Both methods are used to describe simple class information, not much information, but JSON is clearly more concise than XML. Specific differences can be as follows:

  • Readability: JSON and XML are comparable in readability, with easy syntax on the one hand and formal tag form on the other, making it hard to tell the difference
  • Extensibility: XML is naturally extensible, and JSON certainly is, so what XML can scale, JSON can scale
  • Coding difficulty: XML has a wealth of coding tools, such as DOM4J, JDom, etc. JSON also provides many tools. But without tools, because XML has many structural characters, programming is relatively difficult.
  • Decoding difficulty: XML parsing requires consideration of child nodes and parent nodes, which is difficult, while JSON parsing difficulty is almost zero, which seems to understand the data structure

JSON cognitive

JSON has the following form
  • JSON object

{
    "id": "002"."name": "Little Dragon Lady"."sex": "Female"."age": "21"
}
Copy the code

This is a simple JSON object, and we can observe some syntax of JSON:

  1. The data is in curly braces[]
  2. The data toKey: valuePairs (where keys are usually strings and values can be strings, values, or JSON objects)
  3. Every twoKey: valuePairs are separated by commas., the last key-value pair should be omitted.

We can easily build a JSON object based on the above three characteristics

  • JSON array

["value1"."value2"."value3"]
Copy the code

or

[{"id": "001"."name": "Yang guo"."sex": "Male"."age": "20"
    },
    {
        "id": "002"."name": "Little Dragon Lady"."sex": "Female"."age": "21"}]Copy the code

The array representation is also simple:

  1. End by[]The parcel
  2. Data primary key to.separated
  • JSON string

'{"id": "001"."name": "Yang guo"."sex": "Male"."age": "20"} 'Copy the code

JSON strings are very similar to Java strings.

  1. It must be""or' 'Wrap data and support various operations on strings
  2. The data can be a JSON object, a JSON array, or a combination of the two basic forms

This is the basic form of JSON, which can be used in a variety of languages, each with its own implementation. Let’s get familiar with FastJSON in the Java language.

FastJSON

FastJSON is a Java-based JSON parser and generator developed by Alibaba engineers that 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. FastJSON can handle any Java object, including preexisting objects without source code

FastJSON is very easy to use, we just need to introduce the following dependencies in the Maven project POM file:

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

FastJSON API entry class is com. Alibaba. FastJSON. JSON, commonly used serialization operation can be done directly on the JSON class static methods.

API

We have already introduced FastJSON dependencies in the project, and a user class already exists:

@Data
public class User {
    private int id;

    private String name;

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

This is the most common method, serializing javabeans into JSON text

We can turn an object into a JSON string by passing it in, not just a JavaBean but also a Map object

We can also get a JSON string by passing in a Map object. The List object is also useful:

The result is a standard JSONArray string

ToJSONString (Object O, Boolean prettyFormat) : toJSONString(Object O, Boolean prettyFormat) : toJSONString(Object O, Boolean prettyFormat)

JSON formatting makes the output look more clear, which is really sweet ~

Have small partner estimate think these two kinds of I usually all use be bored with slanting, where have in you this see, small dish a think, make sense. Let’s look at the extended use of toJSONString.

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

We can see that this method has a parameter SerializerFeature… The SerializerFeature is an enumeration class. The SerializerFeature is an enumeration class.

Don’t get dizzy when you look at this picture. There are many instances, but most of them are annotated with @deprecated to indicate that they have been deprecated. So what are some of the things that we usually use:

object describe
SerializerFeature.UseSingleQuotes Use single quotes instead of double quotes, default isfalse
SerializerFeature.PrettyFormat Whether to format the result. 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 whose value is NULL. The default value isfalse
SerializerFeature.WriteClassName Write type information when serializing, default isfalse

Use cases:

  • SerializerFeature.UseSingleQuotes

Use single quotes instead of double quotes. Default is false

  • SerializerFeature.PrettyFormat

The result is formatted or not. The default is false

  • SerializerFeature.WriteDateUseDateFormat

If the time is data or timestamp, initialize the time in the format “YYYY-MM-DD HH: MM”.

In this way we print the date in a fixed format: YYYY-MM-DD HH: MM. Sometimes we don’t want this format.

This approach supports custom time format, but use method is toJSONStringWithDateFormat (), to note here, not in the wrong way, then added dishes Cheat philandering man ~ feelings

  • SerializerFeature.WriteMapNullValue

Whether to output fields with a value of null. The default value is false.

This use what use, we should be clear in the specification development to encourage the javabeans pass parameters, decrease as far as possible to pass an argument by Map, because the Map is equivalent to a black box, for users don’t know what are inside field, and estimates for creators will forget there are which fields, in order to solve this pain, JSON also offers a solution:

With the plain old toJSONString() method, null values seem to be eaten, which could be a development disaster!

  • SerializerFeature.WriteClassName

Write type information when serializing. Default is false. This method can be used in deserialization as follows:

This way we can see what type of object we serialize.

ToJSONString extensions toJSONString extensions

Vx Search: Good memories of small dishes

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

  • parseObject(String text)

Serialization, deserialization

Deserialization is converting a JSON-formatted string into a Java Bean object.

We can convert a standard JSON string into a JSONObject, and since the JSONObject class implements the Map interface, we can get the value by getting ().

We already know the fatal weakness of maps, so we’d rather have a JavaBean object.

Of course you can! We get the Javabeans we want by passing in the type of object we want to convert

In addition to basic deserialization, there is a generic deserialization available

With generics, we can get our Javabeans directly without passing in a Class object

Another use of FastJSON serialization is for deep cloning. Those of you who have read my previous article believe that you now have a certain understanding of software design patterns, in which the prototype pattern involves deep cloning and shallow cloning.

The implementation of shallow cloning is quite simple, just implement the Cloneable interface and override the clone() method:

In the result we see the good man card all belong to xiao Wang, this is the drawback of shallow clone. There are a number of ways we want to implement procloning:

  • Manually assign values to reference properties
  • With the help of FastJSON
  • Serialized objects that use Java streams

There are a number of ways to do that, but let’s focus on thatFastJSONThe implementation of:

With FastJSON deserialization, we get two objects that are actually different, which makes it easy to implement deep cloning.

For more on design patterns, please shift:

Create an object in 2021!

Enter “structure model” with pictures and pictures, so simple!

Knock on the blackboard! Here comes Behavioral Patterns

parseArray(String text)

This is a method that converts a JSON string to a JSONArray

We can do the same thing with generic serialization:

The catch with this method is that when we use parseArray() we pass in the second argument the object type we want to deserialize, but we pass in an array. Are you surprised that we have two of the same types in the array? Type[] = ‘List’; Type[] = ‘List’;

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

toJSONBytes(Object o)

Convert JSON objects into arrays of bytes

When we communicate on the network, we need to convert objects into bytes and then transfer them. When we use strings, we can’t help but think of a handy API in strings that can turn strings into byte arrays

String str = "Dishes";
byte[] bytes = str.getBytes();
Copy the code

But if we want to convert a JavaBean object into a byte array, we need the help of the ByteArrayOutputStream stream:

This also works fine for converting JavaBean objects into byte arrays, but the code is a bit too much! FastJSON also provides a handy API to use:

To convert a byte array into an object, FastJSON also supports:

The parseObject() method has an odd parameter called Feature, which is also an enumeration class:

See the same cloud in the fog, so many object instances, we have made a note of the more common:

object describe
AllowUnQuotedFieldNames Determines whether parser will allow non-quoted attribute names
AllowSingleQuotes Determines whether the Parser allows single quotes around attribute names and string values
InternFieldNames Determines if JSON object property names can be normalized by String#intern, and if so, all JSON property names will be intern(); If not set, it will not be normalized, and by default, the property is open.
AllowISO8601DateFormat If the value is set to true, the date class is directly converted when the string meets the date in ISO8601 format
AllowArbitraryCommas Multiple commas are allowed, and if set to true, multiple commas are skipped
UseBigDecimal If set to true, the BigDecimal class is used to load numbers; otherwise, double is used
IgnoreNotMatch Ignore mismatches
DisableCircularReferenceDetect Disable circular reference detection
InitStringFieldAsEmpty Set to empty string for no worthy string property
SupportArrayToBean Support for array to objects
OrderedField Attributes remain in their original order
DisableSpecialKeyDetect Disable special character check
UseObjectArray Using object arrays
writeJSONString(OutputStream os, Object o)

This method writes an object to the output stream:

The argument passed can also be a Writer object:

These are the apis we usually use, in addition to FastJSON, there is another annotation @jsonField that we should learn to use flexibly

@JSONField
After remodeling

Note: If the attribute is private, it must have a set() method, otherwise it cannot be deserialized!

@jsonField is simple to use and can be configured on getters (), setters (), or property fields

Test results:

The best advantage of this method is used for butt joint of many documents, why say strange, sometimes we need to call third-party interface, but a return value of the interface may be not in conformity with the naming conventions, then we need to define an entity class to receive it (although the Map, but also not specification).

In this case, we define the attribute name of the entity class according to the name of the returned field, which is fatal to the ocD program monkey, this time the use of @jsonField, let’s look at a simple example. The return field of a license plate information entity looks like this:

{"PLATEID" : 01."PLATE": 'fujian A6666D',"IMAGEURL":'http:/ /... '}
Copy the code

We can see that all returned field names do not meet the small hump rule. This is not the case with our defined entity class. We can write @jsonField as follows:

Test whether the result can be received successfully:

You can see that we have successfully received the result, and the entity class is named according to our specification, killing two birds with one stone.

DataFormat

We can also use this annotation to format our dates the way we want

Control serialization

During serialization or deserialization we can specify that the field is not serialized, which is a bit like a transient modifier in a Java stream. Similar functionality can be implemented in FastJSON:

The drawback of deserialization is that although the value is empty, the attribute name is still in ~

ordinal

We can use ordinal to specify the order of fields

By receiving the result, we can see that the attribute fields are arranged according to the order specified by us. The usefulness can be that when we return too many fields to the front end, we will prioritize the useful fields to the front, so that we can better value, instead of searching the required fields layer by layer.

Custom serialization

Everything can be customized, serialization is no exception ~ we can use serializeUsing to specify the attributes of the serialized class

In this way we treat the age property, assigning units to the specified field.

This article is about the use of FastJSON, I hope you can bring moderators, long road, small dish with you to seek ~

Today you work harder, tomorrow you will be able to say less words!

I am xiao CAI, a man who studies with you. 💋

Wechat public number has been opened, xiao CAI Liang, did not pay attention to the students remember to pay attention to oh!

Each is the taste of first love oh ~