【发布时间】:2017-02-23 15:58:46
【问题描述】:
[{
"surveyid": 1
}, {}, {}, {}, {}, {}, {}, {
"question": "1"
}, {
"answer": "john"
}, {
"question": "2"
}, {
"answer": "Male"
}, {}, {
"question": "3"
}, {}, {
"answer": "Fishes"
}, {
"answer": "Cats"
}, {
"answer": "Dogs"
}]
这是我用这段代码制作 json 数组的结果:
JSONArray myArray = new JSONArray();
try {
for (View touchable: allTouchables) {
JSONObject j = new JSONObject();
String className = touchable.getClass().getName();
if (className.equalsIgnoreCase("android.widget.TextView")) {
TextView textview = (TextView) touchable;
String tag = (String) textview.getTag();
System.out.println("tag " + tag);
if (tag.matches("questions")) {
String questionid = textview.getText().toString().split("[\\(\\)]")[1];
System.out.println("TextView touchable " + questionid);
j.put("question", questionid);
} else if (tag.matches("surveytitle")) {
int questionid = textview.getId();
System.out.println("TextView touchable " + questionid);
j.put("surveyid", questionid);
}
} else if (className.equalsIgnoreCase("android.widget.RadioButton")) {
RadioButton value = (RadioButton) touchable;
if (value.isChecked()) {
System.out.println("RadioButton " + value.getText().toString());
j.put("answer".toString(), value.getText().toString());
}
} else if (className.equalsIgnoreCase("android.widget.EditText")) {
EditText value = (EditText) touchable;
System.out.println("EditText " + value.getText().toString());
j.put("answer".toString(), value.getText().toString());
} else if (className.equalsIgnoreCase("android.widget.CheckBox")) {
CheckBox value = (CheckBox) touchable;
if (value.isChecked()) {
System.out.println("CheckBoxButton " + value.getText().toString());
j.put("answer", value.getText().toString());
}
}
myArray.put(j);
System.out.println("myArray j " + j);
}
System.out.println("myArray j " + myArray);
} catch (JSONException e) {
e.printStackTrace();
}
但我想要的格式是:
[{
"surveyid": 1,
"question": "1",
"answer": "john"
}, {
"surveyid": 1,
"question": "2",
"answer": "Male"
}, {
"surveyid": 1,
"question": "3",
"answer": "Fishes"
}, {
"surveyid": 1,
"question": "3",
"answer": "Cats"
}, {
"surveyid": 1,
"question": "3",
"answer": "Dogs"
}]
这种数组的制作如何制作这种格式。
任何想法都值得赞赏。
【问题讨论】:
-
为什么不使用 gson 或 jackson?
-
您正在获取所有视图并从中读取一些值,然后将它们添加到您的 JSONArray 中,当然输出会是这样。当您的视图类处于其中一个子句的条件下时,您将一些信息放入 JSONObject 并将其添加到数组中。如果要跟踪问题的答案,则必须跟踪 JSONArray 中的问题对象并获取该问题 JSONObject 并将答案值放入其中。或者最好先创建一个包含问题和答案的 java 问题类,以便您可以轻松跟踪和修改,而不是将其转换为 JSONArray
-
将您的 JSONObject 放在 for 循环之外,否则您将始终在 JSONObject 中获得一个值,因为有
if...else if。 -
@PriyankPatel 我把它拿出来,我得到了所需的格式,但我只得到最后一个值。对于所有元素