Issue
I am doing a project for the Mobile Application Development unit. I am to read and parse the JSON from https://jsonplaceholder.typicode.com/users and display it in a list.
I am unsure on how the JSON can be parsed.
I am currently using the following script, but getting the JSONTypeMismatch error.
Any help is appreciated. Thanks in advance.
try
{
URL url = new URL("https://jsonplaceholder.typicode.com/users");
con = (HttpURLConnection) url.openConnection();
con.connect();
JSONObject jBase = new JSONObject(IOUtils.toString(con.getInputStream(), StandardCharsets.UTF_8));
JSONArray data = new JSONArray(IOUtils.toString(con.getInputStream(), StandardCharsets.UTF_8));
for (int i = 0; i < data.length(); i++)
{
JSONObject user = data.getJSONObject(i);
users.add(new User(user.getInt("id"), user.getString("name"), user.getString("username"), user.getString("email"), user.getJSONObject("address"), user.getString("phone"), user.getString("website"), user.getJSONObject("company")));
}
}
catch (MalformedURLException e) {Toast.makeText(getApplicationContext(), "Malformed URL!", Toast.LENGTH_SHORT).show();}
catch (IOException e) {Toast.makeText(getApplicationContext(), "IOException!", Toast.LENGTH_SHORT).show();}
catch (IllegalStateException e) {Toast.makeText(getApplicationContext(), "HTTP Error!", Toast.LENGTH_SHORT).show();}
catch (JSONException e) {e.printStackTrace();}
finally {con.disconnect();}
Solution
To parse json into an object there are a couple of libraries you can use which makes it easier to parse. One of which is GSON Library
First add Gson to your app level gradle file.
implementation 'com.google.code.gson:gson:2.9.1'
After that you can use below code to parse your required json. This is an example to parse a JSONObject to an object class. Array can be parsed a bit differently
User userModel = new Gson().fromJson(
json.optJSONObject("data").toString(),
User.java)
To parse JsonArray as in your case below code can be used.
Gson gson = new Gson();
String jsonOutput = json.optJSONArray("data").toString();
Type listType = new TypeToken<List<User>>(){}.getType();
List<User> userList = gson.fromJson(jsonOutput, listType);
Answered By - Shahnawaz Ansari
Answer Checked By - David Marino (JavaFixing Volunteer)