如何在Android中解析JSON?
问题描述:
如何在Android中解析JSON提要?
How do I parse a JSON feed in Android?
答
Android具有解析内置json所需的所有工具.示例如下,不需要GSON或类似的东西.
Android has all the tools you need to parse json built-in. Example follows, no need for GSON or anything like that.
获取您的JSON:
假设您有一个json字符串
Assume you have a json string
String result = "{\"someKey\":\"someValue\"}";
创建 JSONObject :
Create a JSONObject:
JSONObject jObject = new JSONObject(result);
如果您的json字符串是一个数组,例如:
If your json string is an array, e.g.:
String result = "[{\"someKey\":\"someValue\"}]"
然后您应该使用下面显示的JSONArray
而不是JSONObject
then you should use JSONArray
as demonstrated below and not JSONObject
获取特定字符串
String aJsonString = jObject.getString("STRINGNAME");
获取特定的布尔值
boolean aJsonBoolean = jObject.getBoolean("BOOLEANNAME");
获取特定整数
int aJsonInteger = jObject.getInt("INTEGERNAME");
获取特定的时间
long aJsonLong = jObject.getLong("LONGNAME");
要获得特定的双打
double aJsonDouble = jObject.getDouble("DOUBLENAME");
要获取特定的 JSONArray :
To get a specific JSONArray:
JSONArray jArray = jObject.getJSONArray("ARRAYNAME");
要从数组中获取项目
for (int i=0; i < jArray.length(); i++)
{
try {
JSONObject oneObject = jArray.getJSONObject(i);
// Pulling items from the array
String oneObjectsItem = oneObject.getString("STRINGNAMEinTHEarray");
String oneObjectsItem2 = oneObject.getString("anotherSTRINGNAMEINtheARRAY");
} catch (JSONException e) {
// Oops
}
}