Preliminary notes on the use of Java’s JSON format conversion library gson

Now there are some open source projects that can convert Java objects into JSON. But most projects require you to add Java annotations to class files, which you can't do when you can't change the source code. And they do not support Java generics. But gson takes these two points as his very important design goals.

characteristic:

The application of gson mainly includes two conversion methods: tojason and fromjason. Before using this object conversion, you need to create the object class and its members to successfully convert the JSON string into the corresponding object.

Code analysis:

When converting JSON into an object, the above code obtains the input stream from the server, encapsulates the input stream into a BufferedReader object, and then converts JSON into a Java object through the fromjson () method.

The first parameter of gson's fromjason () method supports string, jsonelement and reader type parameters, which can be selected as needed. The second parameter of the fromjason () method supports type and class Class can be used when converting JSON to JavaBean Parameter, that is, use the JavaBean corresponding to the JavaBean Calss as the second parameter. When it is necessary to transfer out JSON into list generic type and map generic type, it is necessary to use typetoken to convert the second parameter into type type (typetoken is the data type converter provided by gson and can support the type conversion of various data sets).

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>