2016-02-11 68 views
7

有沒有簡單的方法來轉換嵌套對象如何轉換爲JSON?我試圖創建一個JSON對象來匹配後端。我正在使用Retrofit進行網絡連接,它使用Gson將對象轉換爲JSON。Gson - 將嵌套對象序列化爲屬性

我沒有訪問網絡調用和轉換之間的任何代碼,所以我試圖找到一個乾淨的方式來修改如何通過GsonBuilder或註釋轉換對象。

// Automatically converted to JSON with passed in Gson. 
Call<myObject> search(@Body foo myFoo); 

public class foo { 
    String text = "boo"; 
    bar b = new bar(); 
} 

public class bar { 
    String other = "moo"; 
} 

結果:

{ "text": "boo", "b" { "other": "moo" } } 

所需的結果:

{ "text": "boo", "other": "moo" } 

感謝您的幫助。 :)

+0

您可以使用String other定義用於JSON轉換/從轉換中使用的虛擬類;字符串文本;並吸氣劑安裝者。 @Awestruck – pratikpawar

回答

4

更新我看着GsonBuilder,是的,你可以做自定義序列化。您需要覆蓋serialize方法JsonSerializer<type>

只需定義一個類如下。這裏只添加了2個屬性。

public class FooSerialize implements JsonSerializer<foo> { 

@Override 
    public JsonElement serialize(foo obj, Type foo, JsonSerializationContext context) { 

     JsonObject object = new JsonObject(); 
     String otherValue = obj.b.other; 
     object.addProperty("other", otherValue); 
     object.addProperty("text", obj.text); 
     return object; 
    } 
    } 

創建gson對象如下。

Gson gson = new GsonBuilder().registerTypeAdapter(foo.class, new FooSerialize()).setPrettyPrinting().create(); 

只是轉換成JSON

gson.toJson(fooObject); 

瞧!如果它適用於你,則爲lmk。我在我的系統上測試過它的工作。忘掉字符串重寫它被稱爲Json到Obj的轉換。這只是需要處理反序列化以反對的序列化。尋找在線資源以獲得類似線路的想法。

替代解決方案將僅爲JSON轉換目的定義虛擬pojos。在發送使用setter將值分配給pojo對象並在pojo上使用gson反之亦然或者上面的解決方案來爲您需要的類定製序列化和反序列化。

+0

我在尋找更通用的解決方案,因爲我的bar類包含一些變量,而且我不想在所有名稱中進行硬編碼。我正在使用Retrofit,所以它只是使用Gson來轉換對象,所以我沒有任何地方可以調用。的toString(); –

+0

我剛剛嘗試過,並且toString()從未被調用過。在你的例子中,這看起來不像有效的JSON。那是不一樣的嗎? –

+0

感謝您的更新,效果很好!我修改了一下,並將我的代碼發佈爲我自己的答案。 –

1

爲了給我想要完成的東西增加一些細節,讓我展示一下我寫的內容,因爲它可能會幫助別人試圖做同樣的事情。雖然我的父對象(foo)只有一些變量,但我的子對象(bar)有一長串可能的變量。

我確實發現你可以遍歷孩子的條目並手動將它們添加到父級。不幸的是,這有副作用,往往會添加不需要的值,比如我的常量或者值爲'0'的任何整數。

希望這可以幫助別人。

public class FooSerializer implements JsonSerializer<Foo> { 
    @Override 
    public JsonElement serialize(Foo src, Type typeOfSrc, JsonSerializationContext context) { 
     JsonObject object = new JsonObject(); 

     object.addProperty("text", src.text); 

     bar myBar = src.getBar(); 

     // Using the context to create a JsonElement from the child Object. 
     JsonElement serialize = context.serialize(myBar, bar.class); 
     JsonObject asJsonObject = serialize.getAsJsonObject(); 

     // Getting a Set of all it's entries. 
     Set<Map.Entry<String, JsonElement>> entries = asJsonObject.entrySet(); 

     // Adding all the entries to the parent Object. 
     for (Map.Entry<String, JsonElement> entry : entries) { 
      object.addProperty(entry.getKey(), entry.getValue().toString()); 
     }  

     return object; 
    } 
} 
相關問題