Small knowledge, big challenge! This paper is participating in theEssentials for programmers”Creative activities

Usually when we serialize, we directly use Gson to convert the whole object into Json string. If you have read Gson source code, you will find that its internal is actually based on JsonWriter to achieve stream serialization

Let’s take a look at the usage posture of JsonWriter

You first need to get the JsonWriter object, specifying the output stream when you create it

JsonWriter writer = new JsonWriter(new OutputStreamWriter(System.out));
Copy the code

Now let’s see what the serialization output of streams can be

writer.beginObject()
        .name("name").value("A Gray Blog")
        .name("age").value(24)
        .name("email").nullValue()
        .endObject();
writer.close();
Copy the code

Note the implementation above, for ordinary objects, the stream starts with beginObject() and ends with endObject()

In the middle, name specifies the key of the JSON string, and value is the value of the JSON string

For example, the execution output above is

{"name":"A Gray Blog"."age":24."email":null}
Copy the code

If the object has nested objects or arrays, the same is true with beginObject/beginArray

JsonWriter writer = new JsonWriter(new OutputStreamWriter(System.out));
writer.beginObject()
        .name("name").value("A Gray Blog")
        .name("age").value(24)
        .name("email").nullValue()
        .name("skill")
        .beginArray()
        .value("Java")
        .value("Python")
        .endArray()
        .endObject();
writer.close();
Copy the code

The output is as follows:

{"name":"A Gray Blog"."age":24."email":null."skill": ["Java"."Python"]}
Copy the code

A gray contact information

All letter is better than no book, the above content, purely one’s words, due to the limited personal ability, it is hard to avoid omissions and mistakes, such as finding bugs or better suggestions, welcome criticism and correction, not grudging gratitude

  • Personal site: blog.hhui.top
  • Micro Blog address: Small Gray Blog
  • QQ: a gray /3302797840
  • Wechat official account: One Grey Blog