2014-05-15 105 views
-1

嘿,我有這個JSONarray,我想知道如何從數組中獲得值ProductName,descriptioncost從JSONArray獲取值

我用下面的方法來獲得例如像quantity值:

quantitybasket.setText(basket.getString("quantity")); 

當我試圖讓productNamelogcatProductName不包含任何價值。

我需要做些什麼來獲得這些值?

[{"id":4,"quantity":2,"product":{"id":2,"productName":"Audi R8","description":"The best of Audi","cost":1000000.0,"rrp":1500000.0,"product_category":[{"id":2,"category":{"id":1,"categoryname":"Supercars"}},{"id":3,"category":{"id":2,"categoryname":"Sportscars"}}]}}] 

我在Android TextView

TextView productbasket = (TextView) productsListItem 
    .findViewById(R.id.product_name_basket); 

TextView descriptionbasket = (TextView) productsListItem 
    .findViewById(R.id.description_basket); 

TextView costbasket = (TextView) productsListItem 
    .findViewById(R.id.cost_basket); 

TextView quantitybasket = (TextView) productsListItem 
    .findViewById(R.id.quantity_basket); 
+0

你如何反序列化JSON? –

回答

0

每個值保存您可以使用Google gson。與JSON一起使用的優秀Java庫。

在這裏找到:https://code.google.com/p/google-gson/

使用gson庫類,你可以做這樣的事情:

String myJson = "[{\"id\":4,\"quantity\":2,\"product\":{\"id\":2,\"productName\":\"Audi R8\",\"description\":\"The best of Audi\",\"cost\":1000000.0,\"rrp\":1500000.0,\"product_category\":[{\"id\":2,\"category\":{\"id\":1,\"categoryname\":\"Supercars\"}},{\"id\":3,\"category\":{\"id\":2,\"categoryname\":\"Sportscars\"}}]}}]"; 
    JsonElement jsonElement = new JsonParser().parse(myJson); 
    // This is because your json string is an array {} 
    JsonArray myJsonAsArray = jsonElement.getAsJsonArray(); 
    // Now inside the json array, you get an object, so get it first from '0' index 
    JsonObject mainObject = myJsonAsArray.get(0).getAsJsonObject(); 
    // Now you have a 'product' JsonObject inside the main object 
    // You can directly get it by using String name 
    JsonObject productObject = mainObject.getAsJsonObject("product"); 
    // Once you have 'Product' object, you can get individual elements by following 
    String productName = productObject.get("productName").getAsString(); 
    // This will print out "Audi R8" 
    System.out.println(productName); 

    //You know how it works. Now get other individual elements of the product object by name 

我希望這有助於。

+0

非常感謝 – user3476614

+0

@ user3476614由於您對StackOverflow看起來很陌生,因此我應該引導您 - 一旦您提出問題,並且您得到的答案是正確的解決方案,那麼您必須將答案打勾爲已批准的答案,以便其他回來的人對這個問題知道接受的正確的解決方案,也是這樣你的問題將不會列入'未回答'的問題類別。遵守這些準則非常重要,以保持這個社區的清潔和清晰。我希望你明白。 –