user1382272 user1382272 - 2 months ago 9
Java Question

Issue when parsing JSON

I get a very weird error when I tried to parse a JSON.
Effectively, the file is very simple and composed of a simple object as follow :

{
"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 example of the Android SDK :

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 the execution, I get an error rising when performing.

String name = reader.nextName();


The error said that it expects a name but it gets a STRING. To be sure, I replace nextName() by nextString() and I obtained the opposite error : Expected a String but was NAME. I decide to check the first value thanks to the peek() method, and it clearly says that the first element is a NAME. So I tried a very simple thing by reading the object manually, without the loop and it works. How is it possible ? Furthermore, what do I have to modify to make this code workable ?

Thank you !

Answer

try using inbuilt library provided by android sdk

                JSONObject obj = new JSONObject(jsonString);
                boolean registered = obj.getBoolean("registered");
                String firstname = obj.getString("firstname");
                String name = obj.getString("name");
                String email = obj.getString("email");
                String picture = obj.getString("picture");
                String username = obj.getString("username");