我有一个从我的数据库发送的数据数组 - 一旦收到,我将其保存在共享首选项中 - 这是我的吸气剂:
public List getAnswerStringEdit() {
return answer_edit;
}
我保存原样:
editor.putString(Constants.ANSWER_EDIT,resp.getAnswer().getAnswerStringEdit().toString().trim());
然后在此处检索:
String answerString = pref.getString(Constants.ANSWER_EDIT, "").trim();
answerString = answerString.substring(1, answerString.length() - 1).trim();
String[] array = answerString.split(",");
最后,我这样访问数组:
et_answer1_edit.append(array[0]);
我的问题是这样的 - 假设我添加了一个在其中间有逗号的问题,例如 -
问题1-“为什么会破坏,我不知道?”
目前,当我检索我的问题时,字符串会被拆分,即使整个问题/答案周围都有引号 - 所以在上面的例子中,在数组中的位置0,我应该:
“为什么会破坏,我不知道?”
然而,我正处于第0位:
为什么会破坏 - 然后将位置1视为:我不知道
我知道这听起来很糟糕,因为很明显,我要求在逗号上发生拆分,但我希望在整个字符串对象的末尾,而不是在它的中间。
检索到的JSON如下:
{
"result": "success",
"message": "Answer Has Been Selected",
"answer": {
"answer_edit": ["Why is this broke, I don't know?", "What is your favorite song, because I want to know"]
}
}
任何有助于我了解导致此问题的帮助/建议都将非常感激。
答案 0 :(得分:2)
不要使用'来分割字符串,'使用这个
JSONObject jsonObject = new JSONObject(answerString );
JSONArray jsonArray = jsonObject.getJSONObject("answer").getJSONArray("answer_edit");
Log.e("Json Array elements are","First Element : "+jsonArray.get(0)+"\nSecond Element : "+jsonArray.get(1));
String QuestionString1 = jsonArray.get(0).toString();
String QuestionString2 = jsonArray.get(1).toString();
答案 1 :(得分:0)
试试这个
JSONObject jsonObject = new JSONObject("your json response");
try
{
JSONObject data = jsonObject.getJSONObject("answer");
JSONArray jsonArray = data.getJSONArray("answer_edit");
Log.e("=>", "" + jsonArray);
for (int i = 0; i < jsonArray.length(); i++)
{
String value = jsonArray.getString(i);
String[] parts = value.split(Pattern.quote(","));
for (int j=0; j<parts.length; j++)
{
Log.e("Answer String ", "=" + parts[j]);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
<强>输出强>
E/=>: ["Why is this broke, I don't know?","What is your favorite song, because I want to know"]
E/Answer String: =Why is this broke
E/Answer String: = I don't know?
E/Answer String: =What is your favorite song
E/Answer String: = because I want to know
答案 2 :(得分:0)
尝试这个
JSONObject jsonObject = new JSONObject("your json response");
try
{
JSONObject answer= jsonObject.getJSONObject("answer");
JSONArray jsonArrayAnswerEdit = answer.getJSONArray("answer_edit");
Log.e("=>", "" + jsonArrayAnswerEdit);
for (int i = 0; i < jsonArrayAnswerEdit.length(); i++){
String que= jsonArrayAnswerEdit.getString(i);
Log.e("json", i + "=" + que);
}
} catch (JSONException e) {
e.printStackTrace();
}
答案 3 :(得分:0)
在阅读完所有建议答案后,找到了一个简单的解决方案:
首先,我存储了从外部数据库发送的答案 -
final String jsonAnswers = gson.toJson (resp.getAnswer().getAnswerStringEdit());
然后保存在共享pref -
中editor.putString(Constants.ANSWER_EDIT,jsonAnswers);
接下来阅读答案:
String answerString = pref.getString(Constants.ANSWER_EDIT, "").trim();
final String[] array = gson.fromJson (answerString, String[].class);
最后,我可以使用数组中的数据设置Edittext:
et_answer1_edit.append(array[0].trim());
et_answer2_edit.append(array[1].trim());