Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the features of Gson

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces "what are the characteristics of Gson". In daily operation, I believe many people have doubts about the characteristics of Gson. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful for you to answer the doubts about "what are the characteristics of Gson?" Next, please follow the editor to study!

Start with a Bug.

I don't know if you have noticed, but no matter how much you test the program at that time, there will always be Bug after a period of time. Let me give you another example that happens every day: if you check it immediately after you finish writing a blog, you can't find your own typos.

It is said that there is some logic in the brain's handling of current things, and there are psychological factors in it, which I don't understand. Anyway, now the program is out of Bug! Out of Bug! Bug!

The thing is, when the client requests the server to open the interface, we return it in the form of a JSON string, which would normally look like this:

{

"name": "mafly"

"age": "18"

"sex": "male"

}

But this guy named Mafly, he doesn't want you to know if he's male or female. There is no gender, the default value in the program is null, and something unexpected happens when JSON is serialized.

Recreate the Bug.

There are many utility classes for converting Java objects into Json strings and Json strings into objects, such as Gson, Jackson, FastJson, etc. We use Gson, which is developed by Google, and its performance is said to be more powerful. Yeah, yeah, that's what we're using. Take a look at the sample code first:

Public static void main (String [] args) {

HashMap map = new HashMap ()

Map.put ("name", "mafly")

Map.put ("age", "18")

Map.put ("sex", null)

String jsonString = new Gson () .toJson (map)

System.err.println (jsonString)

}

Do you guess the Json string we expected above will be output? However, it will not.

This is how when Sex=null, the tojson method of Gson ignores the null value, so that the serialized Json string that does not contain this property value is output. In fact, our expectation is to output {"sex": ""} or {"sex": null}, so what do we do?

Through the search engine, it is found that there are probably three solutions on the Internet:

Call the toJson (Object src, Type typeOfSrc, JsonWriter writer) method

Register a custom TypeAdapter

Set the serializeNulls property value (recommended)

I have not tested the first two methods, but recommend the third one, which is simple and convenient. The source code is as follows:

GsonBuilder gsonBuilder = new GsonBuilder ()

String jsonString1 = gsonBuilder.serializeNulls () .create () .toJson (map)

System.err.println (jsonString1)

The output meets our requirements, {"sex": null}, as shown in the figure:

Simply go to the source code to take a look, in addition to this setting there are many, it is really too convenient. After calling serializeNulls (), Gson sets the serializeNulls attribute to true, the default is false, and the source code:

Public GsonBuilder serializeNulls () {

This.serializeNulls = true

Return this

}

Get to know Gson again

I read a few lines of Gson source code, I found that it is configurable and numerous features, you can use @ SerializedName annotation to rename attributes, use @ Expose annotation to identify attributes without serialization, key that supports Map is in the form of complex objects, date types are converted to specific formats, and differentiated versions are displayed, which are very commonly used in daily projects, but it seems that we have implemented them before.

I simply set up a UserInfo entity class that contains three attribute values: username, age, and sex. Try to test one or two of them:

1.@Expose wants to output who, and the annotation code is shown in the figure:

Set excludeFieldsWithoutExposeAnnotation (), and the third line below is the output:

How 2.@SerializedName wants to display how to display, the annotation code is shown in the figure:

I want to serialize age and show maflyAge when I serialize it. Now it's fine. The output is as follows:

Different versions of 3.@Since and @ Until have different data. The annotation code is shown in the figure:

To set setVersion (3.2) here, @ Since annotations will not be output until version 3.2, while @ Until annotations are only available before version 3.2. The effect output is as follows:

Of course, there are many features, such as capitalization of field initials, result formatting and so on. I'll throw a brick here, and you can try the rest if you need it.

At this point, the study on "what are the characteristics of Gson" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report