舉例講解Java的JSON類庫GSON的基本用法
GSON這個Java類庫可以把Java對象轉(zhuǎn)換成JSON,也可以把JSON字符串轉(zhuǎn)換成一個相等的Java對象。Gson支持任意復(fù)雜Java對象包括沒有源代碼的對象。
其他的json解析庫還有json-lib;Jackson;com.alibaba.fastjson
小編還是喜歡Google的Gson。
一、使用場景:
java對象和json字符串的相互轉(zhuǎn)換;日志輸出。
例如:
Logger logger = Logger.getLogger(CommonAction.class); Gson g = new Gson(); logger.info(“return:”+g.toJson(map));
二、用法舉例:
1.基礎(chǔ)用法toJson
toJason()方法將對象轉(zhuǎn)換成Json字符串
Gson gson = new Gson(); List persons = new ArrayList(); String str = gson.toJson(persons);
2.基礎(chǔ)用法:fromJson()
Gson提供了fromJson()方法來實(shí)現(xiàn)從Json字符串轉(zhuǎn)化為到j(luò)ava實(shí)體的方法。
比如json字符串為:
[{“name”:”name0”,”age”:0}]
則:
Person person = gson.fromJson(str, Person.class);
提供兩個參數(shù),分別是json字符串以及需要轉(zhuǎn)換對象的類型。
3.避免Unicode轉(zhuǎn)義
例如: {"s":"\u003c"} 我只想簡單的打印成這樣 {"s":"<"} 解決方案: 我只需要 disable HTML escaping. Gson gson = new
GsonBuilder().disableHtmlEscaping().create();
4.排除某些字段
如果一個類A中含有字段field1,它的父類也含有字段field1,那么A對象toJson的時候,就會發(fā)生declares multiple JSON fields named field1。 解決方案1:在類A中去掉字段filed1. 解決方案2:使用Json的@Expose注解 將A類MessageText中需要打印的字段filed1加上注解@Expose 。那么父類中沒有加注解的field1就會被排除掉。
Gson g = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
5.換屬性名字
三、使用示例:
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(); //設(shè)置將類型的屬性進(jìn)行格式轉(zhuǎn)換 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; } } //實(shí)現(xiàn)序列化,反序列化接口 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); } } }
相關(guān)文章
Spring Bean實(shí)例的創(chuàng)建及構(gòu)造器的挑選
這篇文章主要介紹了Spring Bean實(shí)例的創(chuàng)建及構(gòu)造器的挑選,文中有非常詳細(xì)的代碼示例,對正在學(xué)習(xí)java的小伙伴們有很好的幫助,需要的朋友可以參考下2021-04-04Springboot攔截器如何獲取@RequestBody參數(shù)
這篇文章主要介紹了Springboot攔截器如何獲取@RequestBody參數(shù)的操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-06-06JAVA中 redisTemplate 和 jedis的配合使用操作
這篇文章主要介紹了JAVA中 redisTemplate 和 jedis的配合使用操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-02-02Java Floyd算法求有權(quán)圖(非負(fù)權(quán))的最短路徑并打印
這篇文章主要介紹了Java Floyd算法求有權(quán)圖(非負(fù)權(quán))的最短路徑并打印,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-07-07