GSON, the Java class library, can convert Java objects into JSON, or convert JSON strings into an equal Java object. Gson supports arbitrary complex Java objects including objects without source code.
Other json parsing libraries include json-lib; Jackson; com.alibaba.fastjson
I still like Google's Gson.
1. Use scenarios:
Conversion of java objects and json strings; log output.
For example:
Logger logger = Logger.getLogger(CommonAction.class);Gson g = new Gson();logger.info("return:"+g.toJson(map)); 2. Examples of usage:
1. Basic usage toJson
toJason() method converts an object into a Json string
Gson gson = new Gson();List persons = new ArrayList();String str = gson.toJson(persons);
2. Basic usage: fromJson()
Gson provides the fromJson() method to implement the method of converting from Json strings to java entities.
For example, the json string is:
[{"name":"name0","age":0}] but:
Person person = gson.fromJson(str, Person.class);
Provide two parameters, namely the json string and the type of the object that needs to be converted.
3. Avoid Unicode escape
For example: {"s":"/u003c"} I just want to simply print it like this {"s":"<"} Solution: I just need to disable HTML escaping. Gson gson = new
GsonBuilder().disableHtmlEscaping().create();
4. Exclude certain fields
If a class A contains field field1 and its parent class also contains field field1, then when A object to Json, declares multiple JSON fields named field1 will occur. Solution 1: Remove field filed1 in class A. Solution 2: Use Json's @Expose annotation to add the field filed1 to print in Class A MessageText @Expose. Then field1 without annotation in the parent class will be excluded.
Gson g = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
5. Change attribute name
3. Use examples:
import java.lang.reflect.Type;import java.sql.Timestamp;import java.text.DateFormat;import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.Date;import java.util.List;import com.google.gson.Gson;import com.google.gson.GsonBuilder;import com.google.gson.JsonDeserializationContext;import com.google.gson.JsonDeserializer;import com.google.gson.JsonElement;import com.google.gson.JsonParseException;import com.google.gson.JsonPrimitive;import com.google.gson.JsonSerializationContext;import com.google.gson.JsonSerializer;import com.google.gson.reflect.TypeToken;public class GSonDemo { public static void main(String[] args) {// Gson gson = new Gson(); //Set format conversion of properties of type Gson gson = new GsonBuilder().registerTypeAdapter(Timestamp.class, new TimestampTypeAdapter()).setDateFormat("yyyy-MM-dd HH:mm:ss").create(); List<Person> persons = new ArrayList<Person>(); for (int i = 0; i < 10; i++) { Person p = new Person(); p.setName("name" + i); p.setAge(i * 5); p.setInsertTime(new Timestamp(System.currentTimeMillis())); persons.add(p); } String str = gson.toJson(persons); System.out.println(str); List<Person> ps = gson.fromJson(str, new TypeToken<List<Person>>(){}.getType()); for(int i = 0; i < ps.size() ; i++) { Person p = ps.get(i); System.out.println(p.toString()); } System.out.println(new Timestamp(System.currentTimeMillis())); }}class Person { private String name; private int age; private Timestamp insertTime; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Timestamp getInsertTime() { return insertTime; } public void setInsertTime(Timestamp insertTime) { this.insertTime = insertTime; } @Override public String toString() { return name + "/t" + age + "/t" + insertTime; }}//Implement serialization and deserialization interface class TimestampTypeAdapter implements JsonSerializer<Timestamp>, JsonDeserializer<Timestamp> { public JsonElement serialize(Timestamp src, Type arg1, JsonSerializationContext arg2) { DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SS"); String dateFormatAsString = format.format(new Date(src.getTime())); return new JsonPrimitive(dateFormatAsString); } public Timestamp deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { if (!(json instanceof JsonPrimitive)) { throw new JsonParseException("The date should be a string value"); } try { DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SS"); Date date = (Date) format.parse(json.getAsString()); return new Timestamp(date.getTime()); } catch (Exception e) { throw new JsonParseException(e); } }}