从JSONArray获取值

时间:2014-05-15 16:54:26

标签: java android json

嘿,我有这个JSONarray,我想知道如何从数组中获取值ProductNamedescriptioncost

我使用以下方法获取类似quantity的值:

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

当我尝试productName时,logcat表示ProductName不包含任何值。

我需要做些什么才能获得这些价值?

[{"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);

1 个答案:

答案 0 :(得分:0)

您可以使用Google gson。一个优秀的Java库,可以使用JSON。

在此处找到它: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

我希望这会有所帮助。

相关问题