java - 如何在 JSON 中获得某个值?
问题描述
我尝试从 API 的内容中获取引用和作者。因为我只想在 android App 中显示引用和作者。
{
"success": {
"total": 1
},
"contents": {
"quotes": [
{
"quote": "Give me golf clubs, fresh air and a beautiful partner, and you can keep the clubs and the fresh air.",
"length": "100",
"author": "Jack Benny",
"tags": {
"0": "funny",
"1": "golf",
"2": "sports",
"4": "tod"
},
"category": "funny",
"language": "en",
"date": "2020-05-17",
"permalink": "https://theysaidso.com/quote/jack-benny-give-me-golf-clubs-fresh-air-and-a-beautiful-partner-and-you-can-keep",
"id": "CzZGhQUP5nApJRq5BaqiggeF",
"background": "https://theysaidso.com/img/qod/qod-funny.jpg",
"title": "Funny Quote of the day"
}
]
},
"baseurl": "https://theysaidso.com",
"copyright": {
"year": 2022,
"url": "https://theysaidso.com"
}
}
但它发生了错误。我试图将jsonObj.getJSONArray("contents")更改为jsonObj.getJSONArray("quotes")。但是,它也有一个错误,即在引号中不返回任何值。
org.json.JSONException: Value {"quotes":[{"quote":"Give me golf clubs, fresh air and a beautiful partner, and you can keep the clubs and the fresh air.","length":"100","author":"Jack Benny","tags":{"0":"funny","1":"golf","2":"sports","4":"tod"},"category":"funny","language":"en","date":"2020-05-17","permalink":"https:\/\/theysaidso.com\/quote\/jack-benny-give-me-golf-clubs-fresh-air-and-a-beautiful-partner-and-you-can-keep","id":"CzZGhQUP5nApJRq5BaqiggeF","background":"https:\/\/theysaidso.com\/img\/qod\/qod-funny.jpg","title":"Funny Quote of the day"}]} at contents of type org.json.JSONObject cannot be converted to JSONArray
我怎样才能只得到报价和作者?
这是我的编码。
public class MainActivity extends AppCompatActivity {
private TextView TextViewResult;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextViewResult = findViewById(R.id.view);
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://quotes.rest/qod?category=funny&language=en")
.get()
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
if(response.isSuccessful()){
final String MyResponse = response.body().string();
JSONObject jsonObj = null;
try {
jsonObj = new JSONObject(MyResponse);
} catch (JSONException e) {
e.printStackTrace();
}
try {
assert jsonObj != null;
JSONArray contacts = jsonObj.getJSONArray("contents");
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(1);
final String id = c.getString("id");
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
TextViewResult.setText(id);
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
//
// MainActivity.this.runOnUiThread(new Runnable() {
// @Override
// public void run() {
//
// TextViewResult.setText(MyResponse);
// }
// });
}else {
throw new IOException("Unexpected code " + response);
};
}
});
}
}
解决方案
contents
是一个对象而不是一个数组,记住所有 JSON 数组在开始[
和]
结束时都有 JSON 表示。
任何以 JSON 解析器开头{
并且}
是 struct/JSONObject 的东西
您的 for 循环可以固定如下
JSONArray contacts = jsonObj.getJSONObject("contents").getJSONArray("quotes"); // fetch quotes as JSON Array
for (int i = 0; i < contacts.length(); i++) { // Iterate over quotes
String quote = contacts.getJSONObject(i).getString("quote"); // Fetch quote from JSON object
String author = contacts.getJSONObject(i).getString("author"); // Fetch author from JSON object
System.out.println(" quote=" + quote + " author="+author);
}
推荐阅读
- sql-server - 选择具有特定不同值的组
- swiftmailer - Symfony 和 Swift Mailer
- c - crtexe.c - 关于在 VSCode 中调试 C/C++ 文件的问题
- tensorflow - tensorflow保存模型丢失变量
- c# - 如何绑定到 WPF 中的 SelectedValue 数据上下文属性?
- git - 使用 SSH 的 bitbucket 管道出错
- ios - libc++abi.dylib:以 NSException (lldb) 类型的未捕获异常终止:下拉菜单
- node.js - Visual Studio 代码 - 10000 毫秒后无法连接到运行时进程超时
- android - 在 Kotlin 中,纯数据类和具有业务逻辑的普通类之间哪个更好?
- php - laravel默认注销不起作用