Give an example to explain the basic usage of Java JSON class library gson

Gson, a Java class library, can convert Java objects into JSON or JSON strings into an equivalent Java object. Gson supports arbitrary complex Java objects, including objects without source code. Other JSON parsing libraries include JSON lib; Jackson; com. alibaba. Fastjson Xiaobian still likes Google's gson.

1、 Usage scenario: conversion between Java object and JSON string; Log output. For example:

2、 Usage example: 1 Basic usage: the tojason tojason () method converts an object into a JSON string

2. Basic usage: fromjason() gson provides the fromjason() method to convert the JSON string into a Java entity. For example, the JSON string is:

Then:

Two parameters are provided, namely JSON string and the type of object to be converted. 3. Avoid Unicode escape, for example: {"s": "\ u003c"} I just want to print it like this {"s": "<"} solution: I just need to disable HTML escape Gson gson = new

4. Exclude some fields. If a Class A contains field field1 and its parent class also contains field field1, declarations multiple JSON fields named field1 will occur when a object tojason. Solution 1: remove the field filed1. In class A Solution 2: use Jason's @ expose annotation to annotate the field filed1 to be printed in class a messageText with @ expose. Then field1 without annotation in the parent class will be excluded.

5. Change attribute name

3、 Use example:

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
分享
二维码
< <上一篇
下一篇>>