Android中解析JSON数据流

        在上一篇文章中,我用到的是第三方的类库Gson来解析Json数据流,经过仔细研究,发现Android平台自己的类里也有比较好使用的解析方法。虽然JsonReader这个类是SDK3.0以后才能用的,但这里可以用JSONArray类获取一个JSON对象数组,然后逐个获得JSONObject,进而获得自己需要的信息。

相关代码如下:

public class MainActivity extends Activity {
    private TextView textView;
 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        textView = (TextView) findViewById(R.id.textView);
        String data = null;
        String result = "";
        try {
            data = HttpUtils
                    .getData("http://10.16.12.165:8080/JsonTest/JsonTestServlet");
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            JSONArray array = new JSONArray(data);
            for (int i = 0; i < array.length(); i++) {
                JSONObject object = array.getJSONObject(i);
                result += "name: " + object.getString("name") + "  age: "
                        + object.getInt("age") + "   id: "
                        + object.getString("id") + "\n";
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        textView.setText(result);
 
    }
posted @ 2011-10-30 20:20  图形学小菜鸟  阅读(2593)  评论(0编辑  收藏  举报