如何在Android应用程序中解析未命名的JSON数组

时间:2015-04-10 00:05:41

标签: android arrays json parsing

我有一个通过PHP从我的SQL服务器发送的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"
}
]

我已经在JSONLint验证了我的JSON,它有效。我的HTTP客户端处理后,我还使用日志代码在Eclipse应用程序调试器中打印出我的JSON,并且工作正常(它显示了上面的JSON,所以我知道它已正确下载)。

我正在尝试将JSON Parser放入以下活动中,但到目前为止我所有的尝试都包含太多错误要么运行,或者由于JSON解析错误而没有返回任何结果。

以下是主要活动的代码。此活动的代码改编自NewThinkTank.com(Android Development 15),我正在尝试根据我的需要调整它,但示例中使用的JSON结构与我的非常不同。

我希望有人可以建议一些代码,或者给我一些指示,关于如何正确解析这个JSON数组。我是Android编程的新手,所以这是一个相当陡峭的任务,我自己搞清楚。

感谢您的时间。

public class MainActivity extends Activity {

// The JSON REST Service I will pull from
static String dlquiz = "http://exampleserver.php";


// Will hold the values I pull from the JSON 
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){}
        }

        //this allowed me to verify the JSON download in the debugger
        Log.v("JSONParser RESULT ", result);

        // JSON parsing needs to happen here...



        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);

    }

}

}

1 个答案:

答案 0 :(得分:1)

检查此答案:How to parse JSON in Android

您将使用:

    JSONArray array = new JSONArray(result);

从那里开始,你将遍历并获取每个JSONObject:

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");

    //or if on the MainUI thread you can set your TextView from here:
    yourTextView.setText(obj.getString("placename"));
}
祝你好运!