2014-02-23 42 views
1

我想這樣做來創建一個像下面這樣的json對象。爲什麼原始數組不允許添加到GSON的JSON結構中

JsonObject  request    = new JsonObject(); 
request.addProperty("requestid", UUID.randomUUID().toString()); 
request.addProperty("type", "hotel"); 
request.addProperty("markups", new double[]{1.0,2.0,3.0}); // This says "The method addProperty(String, String) in the type JsonObject is not applicable for the arguments (String, double[])" 
request.add("markups", new double[]{1.0,2.0,3.0});// This says "The method add(String, JsonElement) in the type JsonObject is not applicable for the arguments (String, double[])" 

JSON對象:

{ 
    "requestid": "05afcd81-9c59-4a21-a61e-ae48fda6bdd0", 
    "type": "hotel", 
    "markups": [1.0,2.0,3.0] 
} 

請注意,這是不是,fromJson和的toJSON事情。它是JSON創建和讀取對象不是轉換。 那麼,我怎樣才能做到這一點與上述實施。

+0

它不清楚你在問什麼。它明顯的Gson的'JsonObject'沒有你嘗試使用的方法。我猜你需要閱讀文檔並查看'JsonArray'' –

+0

這就是真正的大腦。我也試過JsonArrays。但它只允許添加JSONElements嗎?但我想要一種添加基元數組的方法。我的意思是,如果我們能夠做到這一點,當我們正在轉換。那麼爲什麼它在創建時不被允許? – namalfernandolk

+0

*「爲什麼在創建時不允許?」* - 向作者提問! –

回答

2

這可以通過使用JsonPrimitive完成如下:

JsonObject  request    = new JsonObject(); 
request.addProperty("requestid", UUID.randomUUID().toString()); 
request.addProperty("type", "hotel"); 

JsonArray  jpArray   = new JsonArray(); 
jpArray.add(new JsonPrimitive(1.0)); 
jpArray.add(new JsonPrimitive(2.0)); 
jpArray.add(new JsonPrimitive(3.0)); 

request.add("markups", jpArray); 

輸出:

{ 
    "requestid": "6259f169-3a55-4a2e-b03c-5931d4daf2fd", 
    "type": "hotel", 
    "markups": [ 
    1.0, 
    2.0, 
    3.0 
    ] 
} 
+0

絕對傳說 –

2

既然你要使用的解析樹對象,以建立自己的JSON結構,您可能需要實例化和將這些值添加到JsonArray對象,或者使用Gson並將其轉換爲double[]。我假設你寧願選擇後者:

public static void main(String[] args) 
{ 
    double[] d = new double[] { 1.0, 2.0}; 
    JsonElement e = new Gson().toJsonTree(d); 
    JsonObject o = new JsonObject(); 
    o.add("array", e); 
    System.out.println(o); 
} 

輸出:

{ 「數組」:[1.0,2.0]}

toJsonTree()方法需要你的Java數組並將其轉換爲Gson解析樹JsonArray並作爲超類返回它JsonElement

+0

謝謝Brian。好一個!。我用JsonPrimitives發現了另一種方式。 – namalfernandolk

相關問題