2013-12-11 10 views
11

我有一個包含一些任意json的String對象。我想將其包裝內的另一個JSON對象,像這樣:使用Gson添加現有的json字符串

{ 
    version: 1, 
    content: >>arbitrary_json_string_object<< 
} 

我怎樣才能可靠地將我的JSON字符串作爲它的一個屬性,而不必手動構建它(即避免了繁瑣的字符串連接)?

class Wrapper { 
    int version = 1; 
} 

gson.toJson(new Wrapper()) 
// Then what? 

注意,添加JSON應該逃脫,但被包裝爲一個有效的JSON實體的一部分,就像這樣:

{ 
    version: 1, 
    content: ["the content", {name:"from the String"}, "object"] 
} 

給出

String arbitraryJson = "[\"the content\", {name:\"from the String\"}, \"object\"]"; 
+0

您是否嘗試添加'content'字符串字段?我很好奇看到結果。 – everton

+0

可能內容將會被轉義。 – 2013-12-11 15:09:27

+0

你解決了你的問題嗎? – giampaolo

回答

5

這是我的解決方案:

Gson gson = new Gson(); 
    Object object = gson.fromJson(arbitraryJson, Object.class); 

    Wrapper w = new Wrapper(); 
    w.content = object; 

    System.out.println(gson.toJson(w)); 

在那裏我改變了你的Wrapper類:

// setter and getters omitted 
public class Wrapper { 
    public int version = 1; 
    public Object content; 
} 

您也可以編寫自定義序列爲您Wrapper,如果你想隱藏反序列化/序列化的細節。

2

您需要首先反序列化它,然後將其添加到您的結構中並重新序列化整個事物。否則,包裝器將只包含完全轉義字符串中的包裝JSON。

這是假設你有一個字符串以下內容:

{"foo": "bar"} 

,並希望它裹在你的Wrapper對象,導致JSON看起來像這樣:

{ 
    "version": 1, 
    "content": {"foo": "bar"} 
} 

如果你沒有首先不反序列化,則會導致以下結果:

{ 
    "version": 1, 
    "content": "{\"foo\": \"bar\"}" 
} 
+0

不,你不需要。您可以使用下面使用「LinkedTreeMap」的中介'JsonObject'。 –

+0

@SotiriosDelimanolis:我不認爲這是我認爲OP正在努力實現的。我編輯了我的答案,使我的意圖更加明顯。 – jwueller

5

Simple,co將你的豆轉換爲JsonObject並添加一個屬性。

Gson gson = new Gson(); 
JsonObject object = (JsonObject) gson.toJsonTree(new Wrapper()); 
object.addProperty("content", "arbitrary_json_string"); 
System.out.println(object); 

打印

{"version":1,"content":"arbitrary_json_string"} 
+0

如果''arbitrary_json_string「'是一個JSON *對象*,這是否工作? – 2013-12-11 15:14:21

+1

@LutzHorn你可以使用'JsonObject#add(JsonElement)'。 –

1

如果你不關心整個JSON結構,你並不需要使用的包裝。你可以將它反序列化爲一個通用的json對象,並在此之後添加新的元素。

JsonParser parser = new JsonParser(); 
JsonObject obj = parser.parse(jsonStr).getAsJsonObject(); 
obj.get("version"); // Version field 
7

對於那些冒險在這個話題上,考慮this

A a = getYourAInstanceHere(); 
Gson gson = new Gson(); 
JsonElement jsonElement = gson.toJsonTree(a); 
jsonElement.getAsJsonObject().addProperty("url_to_user", url); 
return gson.toJson(jsonElement);