【发布时间】:2015-06-16 01:19:27
【问题描述】:
我有一个关于 Android 中 JSON 解析的具体问题。
我需要下载一个包含以下格式信息的 JSON 数组,数组中 JSON 对象的数量是可变的。我需要检索数组中的所有 JSON 值,因此每个 JSON 值都必须存储为一个以公共 JSON 键命名的 android 列表,因为每个都有很多实例,例如地名键列表 [place1,place2,place3 = 地名列表],问题键列表等。需要注意的是,我不能使用 android 数组来存储这些 JSON 键值,因为每次我的应用程序运行此下载任务我不知道单个数组中有多少 JSON 对象。用户可以随时向数据库提交任意数量的内容。
[
{
"placename": "place1",
"latitude": "50",
"longitude": "-0.5",
"question": "place1 existed when?",
"answer1": "1800",
"answer2": "1900",
"answer3": "1950",
"answer4": "2000",
"correctanswer": "1900"
},
{
"placename": "place2",
"latitude": "51",
"longitude": "-0.5",
"question": "place2 existed when?",
"answer1": "800",
"answer2": "1000",
"answer3": "1200",
"answer4": "1400",
"correctanswer": "800"
},
{
"placename": "place3",
"latitude": "52",
"longitude": "-1",
"question": "place 3 was established when?",
"answer1": "2001",
"answer2": "2005",
"answer3": "2007",
"answer4": "2009",
"correctanswer": "2009"
}
]
下面是我的 mainactivity 代码,我设法开始工作,但有一个糟糕的时刻,并意识到我只是简单地完成了每个对象中每个 JSON 键的值并将其解析为每个 JSON 键的单个字符串值。由于循环迭代它只是在每个阶段覆盖 - 地名字符串是“place1”,然后是“place2”,然后是循环结束时的“place3”,而不是[“place1”,“place2”,“place3”]这就是我想要的。我现在的问题是我将如何解析 JSONArray 以提取每个 JSON 值的所有实例并输出为每个 JSON 键的字符串列表,列表的长度由对象的数量决定?
我已经获得了用于存储所有 JSON 键值的字符串列表的模板(在下面的代码中已注释掉),但我不确定如何从 JSON 解析过程中填充该字符串列表。
我环顾四周,找不到任何关于 JSON Array to Android List 的具体信息,因此我们将不胜感激。如果我将数据捆绑到不同的活动(例如问答到测验和地名/纬度/经度到 GPS),我还想知道是否有一种方法可以维护每个列表之间的关联(例如特定地名的问题和答案) )。我可以通过引用列表中的相同索引来做到这一点吗?或者我需要将这些列表存储在本地存储中吗? SQL lite 数据库?
感谢您抽出宝贵时间,并为篇幅过长的帖子感到抱歉!
public class MainActivity extends Activity {
// The JSON REST Service I will pull from
static String dlquiz = "http://www.example.php";
// Will hold the values I pull from the JSON
//static List<String> placename = new ArrayList<String>();
static String placename = "";
static String latitude = "";
static String longitude = "";
static String question = "";
static String answer1 = "";
static String answer2 = "";
static String answer3 = "";
static String answer4 = "";
static String correctanswer = "";
@Override
public void onCreate(Bundle savedInstanceState) {
// Get any saved data
super.onCreate(savedInstanceState);
// Point to the name for the layout xml file used
setContentView(R.layout.main);
// Call for doInBackground() in MyAsyncTask to be executed
new MyAsyncTask().execute();
}
// Use AsyncTask if you need to perform background tasks, but also need
// to change components on the GUI. Put the background operations in
// doInBackground. Put the GUI manipulation code in onPostExecute
private class MyAsyncTask extends AsyncTask<String, String, String> {
protected String doInBackground(String... arg0) {
// HTTP Client that supports streaming uploads and downloads
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
// Define that I want to use the POST method to grab data from
// the provided URL
HttpPost httppost = new HttpPost(dlquiz);
// Web service used is defined
httppost.setHeader("Content-type", "application/json");
// Used to read data from the URL
InputStream inputStream = null;
// Will hold the whole all the data gathered from the URL
String result = null;
try {
// Get a response if any from the web service
HttpResponse response = httpclient.execute(httppost);
// The content from the requested URL along with headers, etc.
HttpEntity entity = response.getEntity();
// Get the main content from the URL
inputStream = entity.getContent();
// JSON is UTF-8 by default
// BufferedReader reads data from the InputStream until the Buffer is full
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
// Will store the data
StringBuilder theStringBuilder = new StringBuilder();
String line = null;
// Read in the data from the Buffer untilnothing is left
while ((line = reader.readLine()) != null)
{
// Add data from the buffer to the StringBuilder
theStringBuilder.append(line + "\n");
}
// Store the complete data in result
result = theStringBuilder.toString();
} catch (Exception e) {
e.printStackTrace();
}
finally {
// Close the InputStream when you're done with it
try{if(inputStream != null)inputStream.close();}
catch(Exception e){}
}
//Log.v("JSONParser RESULT ", result);
try {
JSONArray array = new JSONArray(result);
for(int i = 0; i < array.length(); i++)
{
JSONObject obj = array.getJSONObject(i);
//now, get whatever value you need from the object:
placename = obj.getString("placename");
latitude = obj.getString("latitude");
longitude = obj.getString("longitude");
question = obj.getString("question");
answer1 = obj.getString("answer1");
answer2 = obj.getString("answer2");
answer3 = obj.getString("answer3");
answer4 = obj.getString("answer4");
correctanswer = obj.getString("correctanswer");
}
} catch (JSONException e){
e.printStackTrace();
}
return result;
}
protected void onPostExecute(String result){
// Gain access so I can change the TextViews
TextView line1 = (TextView)findViewById(R.id.line1);
TextView line2 = (TextView)findViewById(R.id.line2);
TextView line3 = (TextView)findViewById(R.id.line3);
// Change the values for all the TextViews
line1.setText("Place Name: " + placename);
line2.setText("Question: " + question);
line3.setText("Correct Answer: " + correctanswer);
}
}
}
【问题讨论】:
-
你快到了。您只需要一个 ArrayList 即可在其中添加值。最好的方法是为所有 Json 项目创建一个 pojo 类,然后通过它添加值。
-
检查here。也许你会受到启发。
标签: java android json arraylist