java - 如何将 JSON 数组解析为 Android 列表

标签 java android json arraylist

这个问题在这里已经有了答案:





JSON parsing using Gson for Java

(11 个回答)



How do I parse JSON in Android? [duplicate]

(3 个回答)



How to parse JSON in Java

(36 个回答)



Sending and Parsing JSON Objects in Android [closed]

(11 个回答)



How to Parse a JSON Object In Android

(4 个回答)


1年前关闭。




我对 Android 中的 JSON 解析有一个相当具体的问题。

我需要下载一个包含以下格式信息的 JSON 数组,数组中 JSON 对象的数量是可变的。我需要检索数组中的所有 JSON 值,因此每个 JSON 值都必须存储为一个以公共(public) 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 的具体信息,因此将不胜感激。如果我将数据 bundle 到不同的 Activity (例如问答到测验和地名/纬度/经度到 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);

    }

}

}

最佳答案

而不是保留变量:

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 类具有所有这些变量。制作 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>();

在json解析的for循环中:
 JSONObject obj = array.getJSONObject(i);
 ModelObject object=new ModelObject();
 // parse and make ModelObject
 list.add(object);

尝试使用这种方法。它会起作用的。

关于java - 如何将 JSON 数组解析为 Android 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29559443/

相关文章:

java - JPanel 中的内容不会出现

java - 将 CPP 应用程序移植到 Android

java - android 应用程序/Activity 生命周期 : when should we save to flash?

android - 以编程方式向 recyclerview 添加新项目?

ios - 从服务器获取 JSON 后如何更新应用程序中的标签?如果应该实时更新

javascript - 通过 Highcharts 从 MySQL 获取 JSON 编码数据时遇到问题

java - 如何根据对象的内容对 ArrayList 进行排序

android - 具有 map Intent 的标记标签

android - 如何访问android中的后退按钮?

json - swift - 表达式太复杂