我对Android中的JSON解析有一个相当具体的问题。
我需要下载包含以下所示格式的信息的单个JSON数组,数组中的JSON对象数量是可变的。我需要检索数组中的所有JSON值,因此每个JSON值必须存储为以常用JSON键命名的android列表,因为每个JSON键都有很多实例,例如地名游戏键列表[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代码,我设法开始工作,但有一个derp时刻,并意识到我只是通过并解析每个对象中每个JSON键的值作为每个JSON的单个字符串值键。由于循环迭代它只是在每个阶段覆盖 - 地名字符串是" place1"然后" place2"然后" place3"在循环结束时,而不是[" place1"," place2"," place3"]这就是我想要的。我现在的问题是如何解析JSONArray以提取每个JSON值的所有实例并输出为每个JSON键的字符串列表,列表的长度由对象的数量决定?
我已经获得了存储所有JSON键值的字符串列表的模板(在下面的代码中注释掉了)但是我不确定如何从JSON解析过程中填充String列表
我已经好好浏览了一下,无法找到关于JSON数组到Android列表的任何内容,所以非常感谢帮助。如果我将数据捆绑到不同的活动(例如q& a到测验和地名/),我也想知道是否有一种方法可以保持每个列表之间的关联(例如,特定地名的问题和答案)。 lat / lon到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);
}
}
}
答案 0 :(得分:0)
而不是保留变量:
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 = "";
使Bean Class具有所有这些变量。制作bean的数组列表,并在解析时创建bean对象并添加到列表中。
Bean类:
public class ModelClass{
private String latitude = "";
private String longitude = "";
private String question = "";
private String answer1 = "";
private String answer2 = "";
private String answer3 = "";
private String answer4 = "";
private String correctanswer = "";
// ....
// Getter Setters and constructors
// .......
}
ArrayList<ModelClass> mList=new ArrayList<ModelClass>();
for for json parsing:
JSONObject obj = array.getJSONObject(i);
ModelObject object=new ModelObject();
// parse and make ModelObject
list.add(object);
尝试使用此方法。它会起作用。
答案 1 :(得分:0)
您应该将对象划分为类,并使用GSON json解析器。
看看如何将json数组解析为对象的答案:
JSON parsing using Gson for Java
一个好的方法是一个类问题,它包含一个名为possibleanswers的子类列表,它们有一个布尔属性(正确:true,不正确:false)来检查用户是否点击了正确的。(/ p>
如果要存储数据,则必须使用sqllite或ActiveAndroid等众多库中的任何一个。
答案 2 :(得分:0)
我看到您正在从远程服务访问此JSON文件。在此基础上,您需要以解决物理JSON文件中有多少实例的方式构建代码。
您的问题在这里:
JSONArray array = new JSONArray(result);
for(int i = 0; i < array.length(); i++)
{
JSONObject obj = array.getJSONObject(i);
您告诉它整个JSON文件都有一个数组,其中包含一个不正确的长度。
Curly Brackets(&#34; {&#34;)代表JSONObject,Square Brackets(&#34; [&#34;)代表JSON数组。
基于您的JSON文件:
[
{
"placename": "place1",
"latitude": "50",
"longitude": "-0.5",
"question": "place1 existed when?",
"answer1": "1800",
"answer2": "1900",
"answer3": "1950",
"answer4": "2000",
"correctanswer": "1900"
},
您正在处理一个JSONArray,此数组必须没有引用名称,而是一个位置索引。
你需要尝试的是什么:
public class ListCreator{
private List<String> placename;
public ListCreator() {
placename = new ArrayList<String>();
}
public void addPlaceName(String s)
{
answers.add(s);
}
public String[] getAnswers()
{
return placename.toArray(new String[1]);
}
}
请记住,这只是该类仅为&#34; placename&#34;字段。
现在来到你的JSON:
您需要为要创建的每个List初始化Vector Variable:
private Vector<ListCreator> placeNameVec;
接下来,您需要为JSONArray的每个部分设置一个方法:
public Vector getPlaceNames(){
return placeNameVector;
}
JSONArray array = new JSONArray(result);
for(int x = 0; x < 3; x++){
JSONObject thisSet = array.getJSONObject(x);
ListCreator placeNames = new ListCreator();
placeNames.addPlaceName(thisSet.getString("placename"));
}
placeNameVec.add(placeNames);
这应该让你继续你想要回答的问题。
所以基本上要记住,你不能指定&#34; array.length()&#34;。
希望这有帮助!
请让我知道结果:)
如果你遇到任何进一步的困难,当我感到困惑时,这Tutorial on JSONParsing确实帮助了我。
一切顺利