自訂GSON類型適配器

來源:互聯網
上載者:User

標籤:json

Exception in thread "main" java.lang.RuntimeException: No-args constructor for class java.sql.Timestamp does not exist. Register an InstanceCreator with Gson for this type to fix this problem.

#關於使用Google GSON 實現Json協議字元協議序列化和還原序列化 時間戳記到Timestame類型轉換失敗問題。

解決方案:定義自己的類型適配器。

以下代碼示範了兩個問題:

1.解決上面說的時間戳記到Timestame類型互轉問題。

2.擴充了一個基於HTTP協議URL字串解析到POJO HttpProtocol 的互轉。

Code 如下:

package com.kevin.luan.service;import java.lang.reflect.Type;import java.sql.Timestamp;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;/** * 實現一個自訂的實行適配器 * <p> * 基於Google GSON 實現JSON解析 * </p> *  * @author kevin LUAN *  */public class GsonTypeAdapterDemo {public static void main(String[] args) {Gson gson = new GsonBuilder().registerTypeAdapter(Timestamp.class, new TimestampAdapter()).registerTypeAdapter(HttpProtocol.class, new HttpProtocolAdapter()).create();String json = "{\"price\":\"1.1001\",\"times\":\"" + System.currentTimeMillis() + "\",\"protocol\":\"http://www.koudai.com/abc/test.do?url=abc\"}";Test pojo = gson.fromJson(json, Test.class);System.out.println("JSON TO POJO:" + pojo);json = gson.toJson(pojo);System.err.println("POJO TO JSON:" + json);}/** * 實現一個類型適配器(TypeAdapter) *  * @author kevin LUAN *  */public static class TimestampAdapter implements JsonSerializer<Timestamp>, JsonDeserializer<Timestamp> {@Overridepublic Timestamp deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException {if (json != null) {try {return new Timestamp(json.getAsLong());} catch (JsonParseException e) {throw e;}}return null;}@Overridepublic JsonElement serialize(Timestamp value, Type type, JsonSerializationContext context) {if (value != null) {return new JsonPrimitive(value.getTime());}return null;}}/** * 基於HttpProtocol的類型適配器 *  * @author kevin LUAN *  */public static class HttpProtocolAdapter implements JsonSerializer<HttpProtocol>, JsonDeserializer<HttpProtocol> {@Overridepublic HttpProtocol deserialize(JsonElement json, Type arg1, JsonDeserializationContext arg2) throws JsonParseException {if (json == null) {return null;} else {try {return new HttpProtocol(json.toString());} catch (Exception e) {e.printStackTrace();return null;}}}@Overridepublic JsonElement serialize(HttpProtocol src, Type arg1, JsonSerializationContext arg2) {return new JsonPrimitive(src.toString());}}/** * 測試 * <p> * JSON->POJO * </p> * <p> * POJO->JSON * </p> *  * @author kevin LUAN *  */public static class Test {private Float price = 1.0f;private Timestamp times;private HttpProtocol protocol;@Overridepublic String toString() {return "price:" + price + "|times:" + times + "|protocl:" + protocol + "";}}/** * HTTP協議POJO *  * @author kevin LUAN *  */public static class HttpProtocol {private String protocol;private String host;private int port = -1;private String uri;private String paramQuery;@Overridepublic String toString() {return protocol + "://" + host + ":" + port + uri + "?" + paramQuery + "}";}public HttpProtocol(String value) {if (value.startsWith("\"") && value.endsWith("\"")) {value = value.substring(1, value.length() - 1);}parserProtocol(value);}private void parserProtocol(String value) {int endIndex = value.indexOf("://");if (endIndex != -1) {protocol = value.substring(0, endIndex);parserHost(value, endIndex + 3);}}private void parserHost(String value, int startIndex) {int endIndex = value.indexOf("/", startIndex);if (endIndex != -1) {host = value.substring(startIndex, endIndex);splitHostPort();parserUri(value, endIndex);} else {host = value.substring(startIndex);splitHostPort();}}private void splitHostPort() {if (host.indexOf(":") != -1) {String host_port[] = host.split(":");host = host_port[0];port = Integer.parseInt(host_port[1]);} else {port = 80;}}private void parserUri(String value, int startIndex) {if (value.indexOf("?", startIndex) == -1) {uri = value.substring(startIndex);} else {int endIndex = value.indexOf("?", startIndex);uri = value.substring(startIndex, endIndex);parserQuery(value, endIndex);}}private void parserQuery(String value, int startIndex) {if (value.indexOf("?", startIndex) != -1) {int paramQueryIndex = value.indexOf("?", startIndex);paramQuery = value.substring(paramQueryIndex + 1);}}}}
運行Main結果:

JSON TO POJO:price:1.1001|times:2014-06-22 13:06:54.138|protocl:http://www.koudai.com:80/abc/test.do?url=abc}

POJO TO JSON:{"price":1.1001,"times":1403413614138,"protocol":"http://www.koudai.com:80/abc/test.do?url\u003dabc}"}



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.