ANDROID_MARS学习笔记_S02_013_Gson解析json串

1.MainActivity.java

 1 package com.json;
 2 
 3 import java.io.IOException;
 4 import java.io.StringReader;
 5 
 6 import android.annotation.SuppressLint;
 7 import android.app.Activity;
 8 import android.os.Bundle;
 9 import android.util.JsonReader;
10 import android.view.View;
11 import android.view.View.OnClickListener;
12 import android.widget.Button;
13 
14 public class MainActivity extends Activity {
15 
16 
17 
18     private String jsonData = "[{\"name\":\"Michael\",\"age\":20},{\"name\":\"Mike\",\"age\":21}]";
19     private Button button ;
20     
21     @Override
22     protected void onCreate(Bundle savedInstanceState) {
23         super.onCreate(savedInstanceState);
24         setContentView(R.layout.activity_main);
25         button = (Button)findViewById(R.id.buttonId);
26         button.setOnClickListener(new OnClickListener() {
27             @Override
28             public void onClick(View v) {
29                 JsonUtils jsonUtils = new JsonUtils();
30                 jsonUtils.parseJson(jsonData);
31             }
32         });
33     }
34     
35     class JsonUtils {
36         @SuppressLint("NewApi")
37         public void parseJson(String jsonData) {
38             JsonReader reader = new JsonReader(new StringReader(jsonData));
39             try {
40                 reader.beginArray();//开始解析数组
41                 while (reader.hasNext()) {
42                     reader.beginObject();//开始解析对象
43                     while (reader.hasNext()) {//开始解析键值对
44                         String tagName = reader.nextName();
45                         if(tagName.equals("name")) {
46                             System.out.println("name-->" + reader.nextString());
47                         } 
48                         else if(tagName.equals("age")) {
49                             System.out.println("age--->" + reader.nextInt());
50                         }
51                     }
52                     reader.endObject();
53                 }
54                 reader.endArray();
55             } catch (IOException e) {
56                 e.printStackTrace();
57             }
58         }
59     }
60 }

 

你可能感兴趣的:(ANDROID_MARS学习笔记_S02_013_Gson解析json串)