ANDROID_MARS学习笔记_S02_014_GSON解析JSON串为对象

 

 1 package com.json2;
 2 
 3 import android.app.Activity;
 4 import android.os.Bundle;
 5 import android.view.View;
 6 import android.view.View.OnClickListener;
 7 import android.widget.Button;
 8 
 9 import com.google.gson.Gson;
10 
11 public class MainActivity extends Activity {
12 
13     private Button button = null;
14     private String jsonData = "{\"name\":\"Michael\",\"age\":20}";
15     
16     @Override
17     protected void onCreate(Bundle savedInstanceState) {
18         super.onCreate(savedInstanceState);
19         setContentView(R.layout.activity_main);
20         button = (Button)findViewById(R.id.buttonId);
21         button.setOnClickListener(new OnClickListener() {
22             @Override
23             public void onClick(View v) {
24                 JsonUitls jsonUtils = new JsonUitls();
25                 jsonUtils.getObjectFromJson(jsonData);
26             }
27         });
28     }
29     
30     public class JsonUitls {
31         public void getObjectFromJson(String jsonData) {
32             Gson gson = new Gson();
33             User user = gson.fromJson(jsonData, User.class);
34             System.out.println(user);
35         }
36     }
37     
38     public class User {
39         private String name;
40         private int age;
41         public String getName() {
42             return name;
43         }
44         public void setName(String name) {
45             this.name = name;
46         }
47         public int getAge() {
48             return age;
49         }
50         public void setAge(int age) {
51             this.age = age;
52         }
53         @Override
54         public String toString() {
55             return "User [name=" + name + ", age=" + age + "]";
56         }
57     }
58 }

 

你可能感兴趣的:(ANDROID_MARS学习笔记_S02_014_GSON解析JSON串为对象)