目前我可以遍历我的JSON数组'' pos “并将其中的所有变量存储到数组列表中。
我正在尝试做什么:
如何轻松解析 tour&日期哪些在“ pos ”数组之外?
我想将值存储在“ tour ”& “日期”分为两个独立的字符串变量。
我的理解: json.getJSONArray()在这种情况下不能用作json.getJSONArray(TAG_MESSAGES);只拉入“pos”数组数据。
JSON结构:
{
"pos": [
{
"pos": "",
"person": "",
"thur": "",
"score": "",
"round": ""
},
{
"pos": "2",
"person": "John",
"thur": "",
"score": "16",
"round": "3"
},
{
"pos": "3",
"person": "Peter Lynch",
"thur": "",
"score": "5",
"round": "2"
}
],
"tour": "Camping",
"date": "Thursday Jul 23 - Sunday Jul 26, 2015"
}
解析JSON pos数组的代码:
// ALL JSON nodes
private static final String TAG_MESSAGES = "pos";
private static final String TAG_ID = "pos";
private static final String TAG_FROM = "person";
private static final String TAG_EMAIL = "thur";
private static final String TAG_SUBJECT = "round";
private static final String TAG_DATE = "score";
// These are outside of array pos
private static final String TAG_TOUR = "tour";
private static final String TAG_TOURDATE = "date";
try {
inbox = json.getJSONArray(TAG_MESSAGES);
inbox.toString();
// looping through All messages
for (int i = 0; i < inbox.length(); i++) {
JSONObject c = inbox.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_FROM, from);
map.put(TAG_EMAIL, mailer);
map.put(TAG_DATE, date);
map.put(TAG_SUBJECT, subject);
// adding HashList to ArrayList
inboxList.add(map);
答案 0 :(得分:2)
因为你可以从你的json获得JSONArray
,你也可以从中获得String
。
类似的东西:
json.getString("tour");
json.getString("date");
答案 1 :(得分:2)
试试这个,
String tour = "", date = "";
try {
if(json.has("tour"))
tour= json.getString("tour");
if(json.has("date"))
date= json.getString("date");
} Catch(Exception e) {
}
即使没有日期/旅游密钥(如果缺少),也不会崩溃
答案 2 :(得分:1)
inbox = json.getJSONArray(TAG_MESSAGES);
String tour=json.getString("tour");
String date=json.getString("date");