preface

As a back-end developer, I will definitely contact data, provide data to the front end or store the data. At present, the most popular transmission format is JSON. It is common to transfer JSON to the front end, or even directly store JSON to the DB.

Json is nothing more than a string at the Java level, and what JSON means to us is to serialize an object or map into a JSON string. So json can do network IO, and you serialize an object into a JSON string and store it in DB, and when you read it out of DB, you read it out as a JSON string, and you have to deserialize it back into an object.

FastJSON is a tool that helps you sequence and deserialize Java objects. It won’t cover advanced usage, just common usage that you will use every day in your work. Here say one more sentence, we may see online every day FastJSON this is not good that is not good…. I know it has bugs, but it’s fast and convenient, and most small businesses will still use FastJSON as a serialization tool of choice.

Pilot packages before starting

/ * here to find the latest package https://mvnrepository.com/artifact/com.alibaba/fastjson * /
<dependency>
 		<groupId>com.alibaba</groupId>
 		<artifactId>fastjson</artifactId>
 		<version>1.257.</version>
</dependency>
Copy the code

serialization

  1. If you don’t know the JSON format, I’ll talk a little bit about the JSON format in serialization, because when you turn Java objects into JSON you can see how JSON stores your objects as strings.

  2. FastJSON(FJ)

    First, FJ has a JSON static utility class that contains the methods we will use next. FJ also provides some other alias classes, such as JSONObject and JSONArray. The names of these classes should be easily known, but the methods provided in this class are JSON, a static tool class. So you can use either one, but I’m going to stick with the JSON class

  3. How to use serialization is to make an object into a format that is easy to transfer and easy to store.

    Json.tojsonstring (the object you want to put in) can convert an object toJSON format

    // Change the map to JSON
    public class MultiTest {
        public static void main(String[] args) {
            // Create a map quickly
            Map<String, String> stuMap = MapUtil.builder("name"."Xiao Ming").
                    put("gender"."Male").build();
            // Serialize the map object using JSON
            String stuJson = JSON.toJSONString(stuMap);
            // The output is {"gender":" male ","name":" xiaoming "}System.out.println(stuJson); }}Copy the code
    // Program the object with json
    public class MultiTest {
    
        @Data
        @Builder
        private static class Student {
            private String name;
            private String gender;
        }
    
        public static void main(String[] args) {
            // Create a map quickly
            Map<String, String> stuMap = MapUtil.builder("name"."Xiao Ming").
                    put("gender"."Male").build();
            // Serialize the map object using JSON
            String stuJson = JSON.toJSONString(stuMap);
            // The output is {"gender":" male ","name":" xiaoming "}System.out.println(stuJson); }}Copy the code
  4. In the example above, you can see that the serialization results of map and entity class are the same. Why? Because entity class and Map are essentially the same, they have one key and one value. Name is key, xiao Hong is value, gender is key, male is value.

    Then we look at the serialized result, {“gender”:” male “,”name”:” xiao Ming “}. We can format json to (there are many tools on the web to beautify JSON, such as www.json.cn)

    {
        "gender": "Male"."name": "Xiao Ming"
    }
    Copy the code

    Json (key) {} (key) {} (key) {} (key) {} (key) {} (key) {} (key) {} (key) {} (key) {} (key); Use commas to separate key – value pairs. This is definitely a list that you’re looking at, but the key-value pair value and the crazy nesting doll, it’s probably still json or an array, or even a JSON array. You can try using json.tojsonString to sequence some of your most frequently used objects and see what it looks like.

deserialization

Since you turned my Java object into a JSON string, there must be a way to change it back and it’s very common.

  • Parse JSON into JSONObject – json.parseObject (put into JSON string)

    So just to explain what a JSONObject is, a JSONObject you can think of as a map, it’s FJ’s implementation of a map, and if you don’t specify what to parse json into it will default to a JSONObject. This object is used just like a map. Here’s an example

        public static void main(String[] args) {
            // Create a map quickly
            Map<String, String> stuMap = MapUtil.builder("name"."Xiao Ming").
                    put("gender"."Male").build();
            // Serialize the map object using JSON
            String stuJson = JSON.toJSONString(stuMap);
    
            // Convert it to JSONObject
            JSONObject jsonObj = JSON.parseObject(stuJson);
            // %s is the class C placeholder to display the following variable contents
            System.out.printf("This student's name is % S and gender is % S % N.",
                    jsonObj.get("name"),
                    jsonObj.get("gender"));
            
            // The result is that the student's name is Xiao Ming and his gender is male
        }
    Copy the code
  • JSONObject is better than Map in some ways, and EMMM is not better than Map, either. Because you’ve changed an Object to JSON, you’ve actually lost its type, or I had a generic constraint, but it’s gone, or I had a Map<String, Object>, and every time you pull an element out of a Map, you have to force it. JSONObject has no generics, but it does cast safely every time it gets. So in JSONObject you can easily get the type you want

The type that a JSONObject can get

So the sout statement in the example I just showed you can be written as

        // %s is the class C placeholder to display the following variable contents
        System.out.printf("This student's name is % S and gender is % S % N.",
                jsonObj.getString("name"),
                jsonObj.getString("gender"));
Copy the code
  • Parse JSON into a Map object – json.parseObject (put in json string, map.class)

    It’s as simple as adding map. class to the parseObject parentheses and specifying that you want to convert to Map

        public static void main(String[] args) {
            // Create a map quickly
            Map<String, String> stuMap = MapUtil.builder("name"."Xiao Ming").
                    put("gender"."Male").build();
            // Serialize the map object using JSON
            String stuJson = JSON.toJSONString(stuMap);
    
            // Convert it to JSONObject
            Map jsonMap = JSON.parseObject(stuJson ,Map.class);
            // %s is the class C placeholder to display the following variable contents
            System.out.printf("This student's name is % S and gender is % S % N.",
                    jsonMap.get("name"),
                    jsonMap.get("gender"));
            // The result is that the student's name is Xiao Ming and his gender is male
        }
    Copy the code

    There’s a caveat here, you’re not going to be able to roll out generics, you’re not going to be safe, or… The ones that look ugly (do you care if it’s not safe, after all)… We can change to a typeReference. You don’t have to care what it is, it’s not very important, it doesn’t matter if you don’t understand it.

        public static void main(String[] args) {
            // Create a map quickly
            Map<String, String> stuMap = MapUtil.builder("name"."Xiao Ming").
                    put("gender"."Male").build();
            // Serialize the map object using JSON
            String stuJson = JSON.toJSONString(stuMap);
    
            // Convert it to JSONObject
            Map<String, Object> jsonMap = JSON.parseObject(stuJson,
                    // Put maps and generics in this reference. Note that this is an anonymous inner class
                    new TypeReference<Map<String, Object>>() {});
            // %s is the class C placeholder to display the following variable contents
            System.out.printf("This student's name is % S and gender is % S % N.",
                    jsonMap.get("name"),
                    jsonMap.get("gender"));
            // The result is that the student's name is Xiao Ming and his gender is male
        }
    Copy the code
  • Parse JSON into a Map object – json.parseObject (put in json string, object.class)

    public class MultiTest {
    
        @Data
        @Builder
        private static class Student {
            private String name;
            private String gender;
        }
    
        public static void main(String[] args) {
            // Create a map quickly
            Map<String, String> stuMap = MapUtil.builder("name"."Xiao Ming").
                    put("gender"."Male").build();
            // Serialize the map object using JSON
            String stuJson = JSON.toJSONString(stuMap);
    
            // Convert it to JSONObject
            Student stuObj = JSON.parseObject(stuJson, Student.class);
            // %s is the class C placeholder to display the following variable contents
            System.out.printf("This student's name is % S and gender is % S % N.",
                    stuObj.getName(),
                    stuObj.getGender());
            // The result is that the student's name is Xiao Ming and his gender is male}}Copy the code
  • Parse JSON to JSONArray– json.parsearray (put in JSON string)

    The JSONArray is similar to the Java list in that it is an FJ implementation of the list. It is also non-generic. You can specify the type to fetch when you get, but I won’t go into details here. Note that the entry to get() is the index subscript, this is a list.

    public class MultiTest {
    
        @Data
        @Builder
        private static class Student {
            private String name;
            private String gender;
        }
    
        public static void main(String[] args) {
            // Here are a few quick maps
            Map<String, String> stuMap1 = MapUtil.builder("name"."Xiao Ming").
                    put("gender"."Male").build();
            Map<String, String> stuMap2 = MapUtil.builder("name"."Xiao gang").
                    put("gender"."Male").build();
            Map<String, String> stuMap3 = MapUtil.builder("name"."Little red").
                    put("gender"."Female").build();
            // Put the map into the list
            List<Map<String, String>> stuList = Arrays.asList(stuMap1, stuMap2, stuMap3);
            // Serialize the list to JSON
            String stuListJson = JSON.toJSONString(stuList);
    
            // Deserialize json to list
            JSONArray stuJsonArray = JSON.parseArray(stuListJson);
            // Element 0 is taken out as a JSONObject
            JSONObject stu1 = stuJsonArray.getJSONObject(0);
            // Element 1 is taken out to become a map. You can also use TypeReference to set generics here
            Map stu2 = stuJsonArray.getObject(1, Map.class);
            // It can even be converted directly to an entity class, since the elements inside are json
            Student stu3 = stuJsonArray.getObject(2, Student.class); }}Copy the code
  • Parse json to list-json. parseArray(put in json string, List element type.class)

    This is usually used a lot, because you can specify the generic type inside, and then return it to help you

    public class MultiTest {
    
        @Data
        @Builder
        private static class Student {
            private String name;
            private String gender;
        }
    
        public static void main(String[] args) {
            // Here are a few quick maps
            Map<String, String> stuMap1 = MapUtil.builder("name"."Xiao Ming").
                    put("gender"."Male").build();
            Map<String, String> stuMap2 = MapUtil.builder("name"."Xiao gang").
                    put("gender"."Male").build();
            Map<String, String> stuMap3 = MapUtil.builder("name"."Little red").
                    put("gender"."Female").build();
            // Put the map into the list
            List<Map<String, String>> stuList = Arrays.asList(stuMap1, stuMap2, stuMap3);
            // Serialize the list to JSON
            String stuListJson = JSON.toJSONString(stuList);
    
            // Deserialize json into a list where each element is studentList<Student> studentList = JSON.parseArray(stuListJson, Student.class); }}Copy the code

After the speech

The above is the more common object and JSON mutual transfer method, in fact, very simple in fact, there are few, so I again to redisk

Object change json json.tojsonString (obj)

Json back to object json.parseObject (json, the object type you want to change to.class)

Json to lsit json.parsearray (json, the type of the element in the list.class)

Is not very simple, in fact, the rule is that they turn each other, FJ to provide us with a very robust and convenient way to turn each other, you can go to see the source code, I am afraid to say too much not too often we see impatient…. Have fun with it

More interesting articles are welcome to my personal blog, click here