如何处理这个Json,在Spinner中提取一次 cat1 值,在第二个Spinner中根据第一个微调器选择我显示 book1 和第二册
JSON:
{
"library":
[
{
"Cat": "cat1",
"Book": "book1",
"authur": "authur1"
},
{
"Cat": "cat1",
"Book": "book2",
"authur": "authur2"
},
{
"Cat": "cat2",
"Book": "book3",
"authur": "authur3"
}
]
}
答案 0 :(得分:0)
你可以简单地使用像Gson或Jackson这样的库来创建域对象(你需要在之前定义它们)。之后,您可以轻松提取您喜欢的任何值。
这是一个例子: http://www.yiiframework.com/doc-2.0/guide-db-query-builder.html
答案 1 :(得分:0)
解析您的JSON
数据并将其存储到ArrayList
并使用Spinner
在ArrayAdapter
上填充。
以下是解析JSON数据的示例代码:
public void parseJson() {
String response = "{\n" +
" \"library\":\n" +
"[\n" +
"{\n" +
" \"Cat\": \"cat1\",\n" +
" \"Book\": \"book1\",\n" +
" \"authur\": \"authur1\"\n" +
" },\n" +
" {\n" +
" \"Cat\": \"cat1\",\n" +
" \"Book\": \"book2\",\n" +
" \"authur\": \"authur2\"\n" +
" },\n" +
" {\n" +
" \"Cat\": \"cat2\",\n" +
" \"Book\": \"book3\",\n" +
" \"authur\": \"authur3\"\n" +
" }\n" +
"]\n" +
"}";
try {
JSONObject mJsonObject = new JSONObject(response);
JSONArray libraryJsonArray = mJsonObject.getJSONArray("library");
ArrayList<String> cats = new ArrayList<>();
ArrayList<String> books = new ArrayList<>();
ArrayList<String> authors = new ArrayList<>();
// Get all jsonObject from jsonArray
for (int i = 0; i < libraryJsonArray.length(); i++)
{
JSONObject jsonObject = libraryJsonArray.getJSONObject(i);
// Cat
if (jsonObject.has("Cat") && !jsonObject.isNull("Cat")) {
cats.add(jsonObject.getString("Cat"));
}
// Book
if (jsonObject.has("Book") && !jsonObject.isNull("Book")) {
books.add(jsonObject.getString("Book"));
}
// Author
if (jsonObject.has("authur") && !jsonObject.isNull("authur")) {
authors.add(jsonObject.getString("authur"));
}
Log.d("SUCCESS", "JSON Object: " + "\nCat: " + cats.get(i)
+ "\nBook: " + books.get(i) + "\nAuthor: " + authors.get(i));
// Do something with ArrayList cats, books and authors
}
} catch (JSONException e) {
Log.e("FAILED", "Json parsing error: " + e.getMessage());
}
}
<强>输出:强>
D/SUCCESS: JSON Object:
Cat: cat1
Book: book1
Author: authur1
D/SUCCESS: JSON Object:
Cat: cat1
Book: book2
Author: authur2
D/SUCCESS: JSON Object:
Cat: cat2
Book: book3
Author: authur3