Json轉換利器Gson之執行個體

來源:互聯網
上載者:User

標籤:

描述

     Gson 是 Google 提供的用來在 Java 對象和 JSON 資料之間進行映射的 Java 類庫。可以將一個 JSON 字串轉成一個 Java 對象,或者反過來

樣本
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();//設定將類型的屬性進行格式轉換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;}@Overridepublic String toString() {return name + "\t" + age + "\t" + insertTime;}}//實現序列化,還原序列化介面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);        }    }}

參考

http://my.oschina.net/sunglasscat/blog/336590

http://www.cnblogs.com/chenlhuaf/archive/2011/05/01/gson_test.html

http://my.oschina.net/itblog/blog/204120

Json轉換利器Gson之執行個體

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.