Android 解析 Json串

来源:互联网 发布:赛尔网络 编辑:程序博客网 时间:2024/06/16 07:23

1.通过主Activity的Button按钮进行解析

public class MainActivity extends Activity {    private Button button=null;    private String jsonData="[{\"name\":\"小张\",\"age\":25,\"sex\":\"男\"},{\"name\":\"小李子\",\"age\":41,\"sex\":\"女\"}," +            "{\"name\":\"倩倩\",\"age\":15,\"sex\":\"女\"}]";    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        button=(Button) super.findViewById(R.id.button);        button.setOnClickListener(new OnClickListener()        {            public void onClick(View v)            {                new JsonUtils(jsonData);            }        });    }    @Override    public boolean onCreateOptionsMenu(Menu menu) {        // Inflate the menu; this adds items to the action bar if it is present.        getMenuInflater().inflate(R.menu.main, menu);        return true;    }    }

2.JosnUtils类用来解析json数据的业务类

public class JsonUtils {    @SuppressLint("NewApi") public JsonUtils(String jsonData)     {        try         {            /**             * 要想解析JSON数据之前先创建一个JsonReader对象,             * 因为JsonReader对象需要一个reader参数所以要把字符串转化成StringReader对象作为参数             */            JsonReader jsonReader=new JsonReader(new StringReader(jsonData));            //开始读取json数据            jsonReader.beginArray();            //循环读取json中的数据,一直到读取数据结束            while(jsonReader.hasNext())            {                //开始读取json对象                jsonReader.beginObject();                //循环读取json对象中的数据,一直到读取数据结束                while(jsonReader.hasNext())                {                    //jsonReader.nextName()读取json对象的名称                    //jsonReader.nextString()读取json对象对应的值;如果是整形对象使用jsonReader.nextInt()方法                    if(jsonReader.nextName().equals("name"))                    {                        System.out.print("姓名:"+jsonReader.nextString());                    }                    if(jsonReader.nextName().equals("age"))                    {                        System.out.print("  年龄:"+jsonReader.nextInt());                    }                    if(jsonReader.nextName().equals("sex"))                    {                        System.out.print("  性别:"+jsonReader.nextString());                    }                }                System.out.println();                //结束json对象数据的解析                jsonReader.endObject();            }            //结束json数据的解析            jsonReader.endArray();        } catch (IOException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }            }    }

3.在运行程序之前要把google的gson-xxx.jar的jar包导入到类库中,下载地址:https://code.google.com/p/google-gson/downloads/list

原创粉丝点击