2013-10-21 17 views
0

全部,如何將Gson擴展爲構造函數併爲任何類型生成默認對象?

Gson激發了我很多,現在我該如何擴展Gson來構建具有某種自定義默認值的任何其他類型的對象。我應該重寫Gson的哪個部分?我真的想重用Gson反射並支持基本類型。但是我發現,在回顧其源代碼之後,基於當前Gson的設計,有一些難以做到的事情。

現在我的要求可以如下表示:

我定義了一個POJO類,如:

TestInputParam.class:

public class TestInputParam{ 
    private Date startTime; 
    private String name; 
    private int num; 

    //setters and gettters 
} 

要求:

GsonEx<TestInputParam> gsonEx = new GsonEx<TestInputParam>(); 
TestInputParam defaultParam = gsonEx.build(TestInputParam.class) 

System.out.println(new Gson().toJson(defaultParam)); 

結果:

It should output this object default value . 

注:

我的理解是:新GSON()fromJson(的StringContent,類型)構建其相應的對象與JsonReader的StringContent價值,只是擴展它可以通過一些默認或隨機值構建其相應的對象。不要讓它的字段值來自stringContent。

+0

對不起,我不明白。如果JSON字符串爲空,是否要求返回具有默認值的對象? – giampaolo

+0

不,我的意思是如何將Gson擴展爲基於其類型的對象構建器。這意味着自動填充一種類型的對象作爲我們在價值工廠定製的一些值。或一些隨機值。 –

回答

0

如果我理解你的問題,你可能正在尋找Gson的類型適配器。這些允許你創建custom serialization and deserialization

比方說,你有以下JSON:

{ 
    "foo": ..., 
    "bar": ..., 

    "testInputParam": { 
    "startTime": {...}, 
    "name": "SomeName", 
    "num": 1 
    }, 

    "someArray": [...]  
} 

例如,你可以寫一個自定義解串器是這樣的:

private class TestInputParamDeserializer implements JsonDeserializer<TestInputParam> { 

    public TestInputParam deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) 
     throws JsonParseException { 

    //This is the actual "testInputParam" JSON object... 
    JsonObject object = json.getAsJsonObject(); 

    //This is the custom object you will return... 
    TestInputParam result = new TestInputParam(); 

    //Fill in the "startDate" field with the current Date instead of the actual value in the JSON... 
    result.setStartDate = new Date(); 

    //Use the actual "name" found in the JSON... 
    result.name = object.get("name").getAsJsonString(); 

    //Fill in the "num" with a random value... 
    result.setNum = new Random().nextInt(); 

    //Finally return your custom object... 
    return result; 
    } 
} 

一旦你寫你的自定義解串器,你只需要添加它與Gson的對象:

GsonBuilder gson = new GsonBuilder(); 
gson.registerTypeAdapter(TestInputParam.class, new TestInputParamDeserializer()); 

現在,只要你使用這個gson對象反序列化JSON字符串,它找到的每個代表TestInputParam類JSON對象時,它會使用自定義反序列化,但你仍然可以使用默認的反序列化JSON字符串休息...


編輯:使用這種方法,你必須爲你想要自定義序列化/反序列化的每個類寫一個自定義序列化器/反序列化器。還有一個名爲TypeAdapterFactory的類,允許您爲一組相關類型創建類型適配器。你可以找到信息和例子on Gson API documentation

+0

是的,你抓住了我的想法,但你的解決方案意味着每個TestInputParam,我們需要逐一寫它們? –

+0

我想實現的是通用類型的通用解決方案。它就像一個對象工廠,它可以創建任何對象,其基本字段具有一些隨機值或自定義值。不僅適用於特殊的POJO,例如:TestInputParam –

+0

@JerryCai,請參閱編輯。 – MikO

相關問題