我想从JSON中解析String类型的数据。我的JSON响应看起来像
[{"order":-1,"number":"5"},{"order":0,"number":"7"},{"order":1,"number":"3"}]
我尝试使用下一个方法:
JSONArray json = new JSONArray("My JSON String");
for (int i = 0; i < json.length(); i++)
{
JSONObject json_staticon = json.getJSONObject(i);
if(json_staticon.getInt("order") == 0) {
return json_staticon.getInt("number");
}
}
但我想使用Google GSON库来解析我的JSON响应,所以...
有什么更好的方法可以使用GSON在number
对象中获取order = 0
值?
谢谢!
答案 0 :(得分:0)
使用Gson
Gson gson = new Gson();
Type collectionType = new TypeToken<List<Orders>>(){}.getType();
List<Orders> details = gson.fromJson(json, collectionType); // json is your json
for (int i = 0; i <details.size(); i++) {
Log.i("Order is ",""+details.get(i).order); // Log the order
Log.i("Order Number is ",""+details.get(i).number);
}
Order.java
public class Orders {
String order,number;
}
记录的值
06-15 04:22:31.282: I/Order is(2464): -1
06-15 04:22:31.282: I/Order Number is(2464): 5
06-15 04:22:31.282: I/Order is(2464): 0
06-15 04:22:31.282: I/Order Number is(2464): 7
06-15 04:22:31.282: I/Order is(2464): 1
06-15 04:22:31.282: I/Order Number is(2464): 3
您也可以使用增强型for循环for (int i = 0; i <details.size(); i++) {
for (Orders orders: details) {