I get a very strange error when I try to parse JSON. In fact, the file is very simple and consists of a simple object:
{
"registered":false,
"firstname":"xxx",
"name":"yyyy",
"email":"yyyy.xxx@gmail.com",
"picture":"xxxxx.jpg",
"username":"xxxy"
}
To parse this file, I used the following code, which is inspired by the Android SDK example:
public static boolean isRegistered(int nmb) {
boolean toReturn = true;
JsonReader reader = null;
try {
reader = new JsonReader(new InputStreamReader(new URL("xxx").openConnection().getInputStream()));
reader.beginObject();
while(reader.hasNext()) {
String name = reader.nextName();
Log.i("Next value", name);
switch (name) {
case "registered":
toReturn = reader.nextBoolean();
break;
case "firstname":
ProfileManager.getInstance().setFirstname(reader.nextString());
break;
case "name":
ProfileManager.getInstance().setName(reader.nextString());
break;
case "email":
break;
case "picture":
break;
case "username":
break;
}
}
reader.endObject();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return toReturn;
}
When I start execution, I get an error message about the execution.
String name = reader.nextName();
The error says that it expects a name but gets STRING. Of course, I replace nextName () with nextString (), and I got the opposite error: I was expecting a string, but there was NAME. I decided to check the first value thanks to the peek () method, and it clearly says that the first element is NAME. So I tried very simply, reading the object manually, without a loop, and it works. How is this possible? Also, what do I need to change to make this code workable?
Thank!