一、解析JSON数据:

首先引入包import org.json.JSONObject;(android sdk 14以后应该自带了 )

Android端的程序解析JSON和JSON数组:

package com.example.helloandroid;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

public class JSONActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_json);
        //JSON 解析
        String strJson = "{\"sid\":\"2\",\"name\":\"张三\"}";
        try {
            JSONObject userObject = new JSONObject(strJson);
            String name = userObject.getString("name");
            Toast.makeText(JSONActivity.this, name, 1000).show();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
        //JSON 数组解析
        String strArrayJson = "[{\"sid\":\"1\",\"name\":\"张三\"},{\"sid\":\"2\",\"name\":\"张四\"}]";
        JSONArray userJsonArray;
        try {
            userJsonArray = new JSONArray(strArrayJson );
            for(int i=0;i<userJsonArray.length();++i){

                JSONObject userJObject = (JSONObject) userJsonArray.get(i);

                String name = userJObject.getString("name");
                Toast.makeText(JSONActivity.this, name, 1000).show();
                }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}

 

相关文章:

  • 2021-05-25
  • 2021-12-06
  • 2022-03-10
  • 2022-02-05
  • 2021-08-13
  • 2022-02-10
  • 2021-09-03
  • 2022-12-23
猜你喜欢
  • 2021-07-21
  • 2021-09-14
  • 2022-12-23
  • 2021-10-17
  • 2021-10-18
  • 2021-06-18
  • 2022-01-25
相关资源
相似解决方案