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();}
CodePudding user response:
Put those library in your gradle file.
//okhttp
implementation(platform("com.squareup.okhttp3:okhttp-bom:4.9.0"))
implementation("com.squareup.okhttp3:okhttp")
implementation("com.squareup.okhttp3:logging-interceptor")
// gson
implementation 'com.google.code.gson:gson:2.9.0'
Put this line in your manifest..
<application
...
android:usesCleartextTraffic="true">
</application>
Create new class as a JsonUtils.java
in your project
public class JsonUtils {
public static String okhttpGET(String url) {
OkHttpClient client = new OkHttpClient.Builder()
.readTimeout(20000, TimeUnit.MILLISECONDS)
.writeTimeout(20000, TimeUnit.MILLISECONDS)
.build();
Request request = new Request.Builder()
.url(url)
.build();
try {
Response response = client.newCall(request).execute();
return response.body().string();
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
public static String okhttpPost(String url, RequestBody requestBody) {
OkHttpClient client = new OkHttpClient.Builder()
.readTimeout(25000, TimeUnit.MILLISECONDS)
.writeTimeout(25000, TimeUnit.MILLISECONDS)
.build();
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
try {
Response response = client.newCall(request).execute();
return response.body().string();
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
}
Now time to read Json
from URL
, so here your url is GET
method.
so where you need to Read Json write just that code...
String json = JsonUtils.okhttpGET("https://jsonplaceholder.typicode.com/users");
try{
JSONArray array = new JSONArray(json);
// continue decode your Json...
for (int i = 0; i < main_array.length(); i ) {
JSONObject object = main_array.getJSONObject(i);
String id = object.getString("id");
String name = object.getString("name");
String username = object.getString("username");
String email = object.getString("email");
JSONObject address_object = object.getJSONObject("address");
String street = address_object.getString("street");
String suite = address_object.getString("suite");
String city = address_object.getString("city");
String zipcode = address_object.getString("zipcode");
JSONObject geo_object = address_object.getJSONObject("geo");
String lat = object.getString("lat");
String lng = object.getString("lng");
String phone = object.getString("phone");
String website = object.getString("website");
JSONObject company_object = address_object.getJSONObject("company");
String company_name = object.getString("name");
String catchPhrase = object.getString("catchPhrase");
String bs = object.getString("bs");
// here you got all variables = id, name, username, email, street, suite, city, zipcode, lat, lng, phone, website, company_name, catchPhrase, bs
}
}catch(Exception e){
}
CodePudding user response:
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);