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);
     
        }
  • 相关阅读:
    最佳调度问题_分支限界法
    运动员最佳配对问题
    最小重量机器设计问题
    实现银行家算法和先进先出算法_对文件读写数据
    n皇后问题_回溯法
    0-1背包_回溯法
    根据前序、中序、后序遍历还原二叉树
    矩阵连乘问题_动态规划
    最长公共子序列_动态规划
    最优二叉查找树_动态规划
  • 原文地址:https://www.cnblogs.com/yangzhenyu/p/2229496.html
Copyright © 2011-2022 走看看