嘿,我有这个JSONarray,我想知道如何从数组中获取值ProductName
,description
和cost
。
我使用以下方法获取类似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);
答案 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
我希望这会有所帮助。