【发布时间】:2015-12-04 11:37:57
【问题描述】:
我正在开发应该读取这个 json 字符串的 android 应用程序:
{
"coord":{
"lon":145.77,
"lat":-16.92
},
"weather":[
{
"id":803,
"main":"Clouds",
"description":"broken clouds",
"icon":"04n"
}
],
"base":"cmc stations"
}
类似的东西。
我可以使用以下方法成功读取"coord" 值:
public Coordinates readCoordinates(JsonReader reader) throws IOException{
double longitude = 0.0; // lon
double latitude = 0.0; // lat
reader.beginObject();
while (reader.hasNext()){
String nameToRead = reader.nextName();
if(nameToRead.equals("lon")){
longitude = reader.nextDouble();
}else if (nameToRead.equals("lat")){
latitude = reader.nextDouble();
}else {
reader.skipValue();
}
}
reader.endObject();
return (new Coordinates(longitude, latitude));
}
我也有类似的阅读"weather"的方法:
public Weather readWeather(JsonReader reader) throws IOException{
int id = 0;
String main = "";
String description = "";
String icon = "";
reader.beginObject();
while (reader.hasNext()){
String nameToRead = reader.nextName();
if(nameToRead.equals("id")){
id = reader.nextInt();
}else if (nameToRead.equals("main")){
main = reader.nextString();
}else if (nameToRead.equals("description")){
description = reader.nextString();
}else if (nameToRead.equals("icon")){
icon = reader.nextString();
}else{
reader.skipValue();
}
}
reader.endObject();
return (new Weather(id, main, description, icon));
}
我不断收到此异常消息Expected BEGIN_OBJECT but was BEGIN_ARRAY
如果我将 reader.beginObject() 更改为 reader.beginArray() 我会得到同样的错误。我也尝试完全删除它,并且发生了同样的错误。
我假设这是由 [ 的引入引起的,但我不确定如何解决这个问题。如果有人知道请帮忙,我将不胜感激,谢谢。
【问题讨论】:
-
您可以使用简单的
JSONObject jsonobject = new JSONObject(yourJsonString);代替JsonReader .. 然后使用String description = jsonObject.getString("description");.....示例:如果您需要“coord” JsonObject,您可以使用JSONObject jsonobject = new JSONObject("coord");然后使用int longitude = jsonObject.getInt("lon"); -
这段代码很明显而且看起来不错...... readWeather 应该在循环中调用并且循环应该用数组(开始和结束)包装......就像在android的文档中一样跨度>
标签: android json jsonreader