preface

Only a bald head can be strong.

Star: github.com/ZhongFuChen…

JSON I believe we are not unfamiliar with him, the front and back end interaction is often to JSON data exchange. Sometimes, JSON is stored directly in the database.

For those of you who don’t understand, why do you want to store JSON in a relational database?

I had similar doubts at the beginning, asked several colleagues, and came to the same conclusion: easy to expand, if the fields don’t need indexes, change frequently, and you don’t want to change the structure of the table, you can store JSON in the database

Although storing JSON is easy to expand, if your MySQL version is still relatively low, it is still difficult to use SQL to find a property in JSON.

And it is only a String from the database, and it is not convenient to write the properties inside the JSON, so we have fastjson for us to use.

This article will give you a brief overview of fastjson usage, which I hope will be helpful. If it helps, give me a thumbs up!

Getting started with FastJSON

The following content sources: github.com/alibaba/fas…

It parses JSON-formatted strings, supports serialization of Java beans to JSON strings, and deserialization from JSON strings to Javabeans

Fastjson advantages: fast speed, wide use, easy to use, complete functions, complete testing (there were a lot of bugs before, now we are forced to upgrade fastjson version through the release process), now use Fastjson upgrade to at least 1.2.60 version

Reasons for fast speed:

1. Write a tool class SerializeWriter similar to StringBuilder.

2. Use ThreadLocal to cache BUFs.

3. Use ASM to avoid reflection

4, integration of JDK implementation of some optimization algorithms

Second, use Fastjson

Let’s start by introducing a fastjson dependency in our POM file:

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

Fastjson is used with three main objects:

  • JSON
  • JSONObject
  • JSONArray

JSONArray and JSONObject inherit JSON:

2.1 a JSON object

JSON this class is mainly used for transformations:

  • Serialize a Java object into a JSON string
  • Deserialize a JSON string into a Java object

So there are three methods that we use a lot:

  • parseObject(String text, Class<T> clazz)
  • parseArray(String text, Class<T> clazz)
  • toJSONString(Object object)

2.2 JSONObject

The JSON object (JSONObject) implements the Map interface because its data is in key-value form:

It is also very simple to use, not much different from using Map (because it is actually the underlying operation Map), commonly used methods:

  • getString(String key)
  • remove(Object key)

2.3 JSONArray

JSONArray is a JSON array. JSON array objects store JSON objects, so the methods in the class are mainly used to directly manipulate JSON objects

The most common methods:

  • getJSONObject(int index)

Third, in actual combat

We already know from the above brief introduction:

  • JSON is used to deserialize strings to Javabeans and Javabeans to JSON
  • JSONObject represents a JSON object, which is operated by MapgetStringAnd other methods to obtain the corresponding value
  • JSONArray represents an array of JSON objects, and underneath it is actually a List, which is used to manipulate JSON objects

Typically, after we get the JSON data from the database, we modify the JSON. For example, a JSON string looks like this:

{
	"formId": "{$formId}"."link": "www.java3y.com"."text": [{
		"name": "java3y"."label": "3y"."value": {
			"value": "{$tureName}"."color": ""."emphasis": ""}}, {"name": "java4y"."label": "3y"."value": {
			"value": "{$title}"."color": ""."emphasis": ""}}, {"name": "java5y"."label": "5y"."value": {
			"value": "Follow my official account for more dry goods."."color": "#ff0040"."emphasis": ""}}]."yyyImg": ""."yyyAge": ""."pagepath": ""
}
Copy the code

We don’t manipulate JSON directly, we convert JSON into our own Javabeans, manipulate javabeans, and serialize to JSONString

The JSON structure above is relatively complex.

  • We can base it onJSONConstructs the corresponding Javabeans
  • useJSONClass deserializes a JSON string into a JavaBean
  • Modify the value of the JavaBean
  • The final will beJavaBeanSerialize to a JSON string

From the JSON structure above, we first abstracted the Text layer into a JavaBean. (Actually the innermost structure is value, but I don’t need to deal with value here, so IT’s not abstract.)

/** * "name": "java3y", * "label": "3y", * "value": { * "value": "{$tureName}", * "color": "", * "emphasis": "*} * * abstracts Text */
public class TextInfo {

    private String name;
    private String label;

    // If you want to process each layer, you need to abstract it
    private Object value;


    // set get ... Welcome to follow my official account: Javay

}
Copy the code

Then abstract the outer layer:

public class ContentValue {
    private String formId;
    private String link;
    // Here is an array, we abstracted it as a List, property named text
    private List<TextInfo> text;

    private String yyyImg;
    private String yyyAge;
    private String pagepath;
    
    // set get ... Welcome to follow my official account: Javay

}

Copy the code

Let’s deserialize:

public static void main(String[] args) {

    // JSON string
    String s = "{\"formId\":\"{$formId}\",\"link\":\"www.java3y.com\",\"text\":[{\"name\":\"java3y\",\"label\":\"3y\",\"value\":{\"valu e\":\"{$tureName}\",\"color\":\"\",\"emphasis\":\"\"}},{\"name\":\"java4y\",\"label\":\"3y\",\"value\":{\"value\":\"{$ti Tle} \ ", \ "color \", \ "\", \ "emphasis \" : \ \ ""}}, {\" name \ ": \" java5y \ ", \ "label \" : \ "5 y \", \ "value \" : {\ "value \" : \ "pay attention to my public, More dry \ ", \ "color \", \ "# ff0040 \" and \ "emphasis \" : \ \ ""}}], \" yyyImg \ ", \ "\", \ "yyyAge \", \ "\", \ "pagepath \", \ "\"}";

    // Deserialize a JSON string into a JavaBean using a JSON object
    ContentValue contentValue = JSON.parse(s, ContentValue.class);
    System.out.println(contentValue);


    }
Copy the code

Deserialization results:

To change the value inside the text, we just need to manipulate the JavaBean:

public static void main(String[] args) {

    // JSON string
    String s = "{\"formId\":\"{$formId}\",\"link\":\"www.java3y.com\",\"text\":[{\"name\":\"java3y\",\"label\":\"3y\",\"value\":{\"valu e\":\"{$tureName}\",\"color\":\"\",\"emphasis\":\"\"}},{\"name\":\"java4y\",\"label\":\"3y\",\"value\":{\"value\":\"{$ti Tle} \ ", \ "color \", \ "\", \ "emphasis \" : \ \ ""}}, {\" name \ ": \" java5y \ ", \ "label \" : \ "5 y \", \ "value \" : {\ "value \" : \ "pay attention to my public, More dry \ ", \ "color \", \ "# ff0040 \" and \ "emphasis \" : \ \ ""}}], \" yyyImg \ ", \ "\", \ "yyyAge \", \ "\", \ "pagepath \", \ "\"}";

    // Deserialize a JSON string into a JavaBean using a JSON object
    ContentValue contentValue = JSON.parse(s, ContentValue.class);
    List<TextInfo> text = contentValue.getText();
    for (TextInfo textInfo : text) {
        textInfo.setName("Java3y");
        textInfo.setLabel("Follow my account.");
    }


    // After modification, deserialize back
    String content = JSON.toJSONString(contentValue);
}
Copy the code

Serialization results:

Easily change fields inside JSON strings.

The last

Overall, Fastjson is convenient enough to use and fast enough, although it’s a little buggy lately.

This has been included in my GitHub featured articles, welcome to Star: github.com/ZhongFuChen…

Happy to export dry Java technology public number: Java3y. The public account has more than 300 original technical articles, massive video resources, beautiful brain map, attention can be obtained!

Thank you very much talent can see here, if this article is written well, feel “three crooked” I have something to ask for praise for attention ️ to share 👥 to leave a message 💬 for warm male I really very useful!!

Creation is not easy, your support and recognition, is the biggest motivation for my creation, we will see you in the next article!