如何在Java中分析JSON



我正在为移动应用程序开发部门做一个项目。我将从https://jsonplaceholder.typicode.com/users并将其显示在列表中。

我不确定如何解析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();}

要将json解析成一个对象,可以使用几个库,这样可以更容易地进行解析。其中之一是GSON Library

首先将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);

将这些库放在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 "";
}
}
}

现在是时候从URL中读取Json了,所以这里的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){

}

最新更新