zoukankan      html  css  js  c++  java
  • 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);
     
        }
  • 相关阅读:
    Vue——data中的属性规范
    python的字符串用法
    python笔录第一周
    Mac下python版本的更新
    我的第一篇博客
    C语言-控制语句(循环)
    C语言-控制语句(分支与跳转)
    C语言-函数
    C语言-数组与指针
    C语言-堆和栈
  • 原文地址:https://www.cnblogs.com/yangzhenyu/p/2229496.html
Copyright © 2011-2022 走看看