我有一个json对象,如下所示
{
"Book1":{"Title1":"Cost1","Title2":"Cost2"},
"Book2":{"Title3 ":"Cost3"},
"Book3":{"Title4 ":"Cost4","Title5 ":"Cost5"},
"Book4":{"Title6":"Cost6","Title7”:”Cost7","Title8”:”Cost8"}
}
我想要检索"标题"的所有值没有任何关键字,我想在一个数组中有{Title1,Title2,Title3,Title4,...}。
下面是我根据Book名称检索的代码,但现在我需要检索所有值
List<String> books=new ArrayList<String >();
try {
JSONObject obj = new JSONObject(loadJSONFromAssetArea());
JSONObject bookJson = obj.getJSONObject("Book1");
Iterator<String> keys= bookJson.keys();
do
{
String keyValue = (String)keys.next();
JSONArray specTitle = obj.getJSONArray(keyValue);
for (int i = 0; i < specTitle.length(); i++) {
books.add(specTitle.get(i).toString());
}
}while(keys.hasNext());
} catch (JSONException e) {
e.printStackTrace();
}
我没有得到如何将键值传递给json对象。 请帮助。
提前致谢
答案 0 :(得分:0)
注意强>
您的 GIVEN Json
无效。
Book1,Book2..
DYNAMIC/UNKNOWN
。
以这种方式使用 Iterator
。
试试这种方式,
JSONObject jOBJ= new JSONObject(loadJSONFromAssetArea());
Iterator iteratorObj = jOBJ.keys();
while (iteratorObj.hasNext())
{
String getJsonObj = (String)iteratorObj.next();
System.out.println("Key: " + Key + "------>" + getJsonObj); // print Book1,Book2..
// Now your work
}
答案 1 :(得分:0)
如果你想解析这个
{
"Book1":{"Title1":"Cost1","Title2":"Cost2"},
"Book2":{"Title3 ":"Cost3"},
"Book3":{"Title4 ":"Cost4","Title5 ":"Cost5"},
"Book4":{"Title6":"Cost6","Title7”:”Cost7","Title8”:”Cost8"}
}
您可以使用此代码来解析json对象,
List<String> books = new ArrayList<String>();
try {
JSONObject obj = new JSONObject(loadJSONFromAssetArea());
JSONObject bookJson, innerObject;
Iterator<String> keys = obj.keys();
do {
String keyValue = (String) keys.next();
if (obj.get(keyValue) instanceof JSONObject) {
bookJson = obj.getJSONObject(keyValue);
Iterator<?> innerKeys = bookJson.keys();
while (innerKeys.hasNext()) {
String innerKey = (String) innerKeys.next();
innerObject = bookJson.getJSONObject(innerKey);
books.add(innerObject.getString(innerKey));
}
}
} while (keys.hasNext());
} catch (JSONException e) {
e.printStackTrace();
}
答案 2 :(得分:0)
尝试这是有效的
JSONObject jsonObject = new JSONObject(loadJSONFromAssetArea());
List<String> books=new ArrayList<String >();
try {
Iterator iteratorObj = jsonObject.keys();
while (iteratorObj.hasNext())
{
String getJsonObj = (String)iteratorObj.next();
System.out.println("Book No.: " + "------>" + getJsonObj);
JSONObject jo_inside = jsonObject.getJSONObject(getJsonObj);
//JSONObject jo_inside = new JSONObject((String) iteratorObj.next());
Iterator<String> keys = jo_inside.keys();
while (keys.hasNext())
{
String key = keys.next();
String value = jo_inside.getString(key);
Log.v("Book Title key", key);
Log.v("Book Name value", value);
books.add(jo_inside.getString(key));
}
}
} catch (JSONException e) {
e.printStackTrace();
}