我正在为移动应用程序开发单元做一个项目。我将从https://jsonplaceholder.typicode.com/users中读取和解析JSON,并将其显示在列表中。
我不确定如何解析JSON。
我目前正在使用下面的脚本,但是得到了JSONTypeMismatch错误。
任何帮助都是非常感谢的。提前谢谢。
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();}发布于 2022-09-28 04:45:18
要将json解析为对象,可以使用几个库,这使得解析变得更容易。其中之一是GSON图书馆
首先,将Gson添加到应用程序级别的gradle文件中。
implementation 'com.google.code.gson:gson:2.9.1'之后,您可以使用下面的代码来解析所需的json。这是一个将JSONObject解析为对象类的示例。数组可以进行稍微不同的分析。
User userModel = new Gson().fromJson(
json.optJSONObject("data").toString(),
User.java)要像下面这样解析JsonArray,可以使用代码。
Gson gson = new Gson();
String jsonOutput = json.optJSONArray("data").toString();
Type listType = new TypeToken<List<User>>(){}.getType();
List<User> userList = gson.fromJson(jsonOutput, listType);发布于 2022-09-28 04:26:19
把那些库放到你的gradle文件里。
//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'把这一行放进你的名单..。
<application
...
android:usesCleartextTraffic="true">
</application>将新类创建为项目中的JsonUtils.java
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 "";
}
}
}现在是从Json读取URL的时候了,这里您的url是GET方法。
所以你需要读的地方Json只写这段代码..。
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){
}https://stackoverflow.com/questions/73875388
复制相似问题