package com.example.s02_e12_json3; import java.lang.reflect.Type; import java.util.Iterator; import java.util.LinkedList; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; public class MainActivity extends Activity { private Button button = null; private String jsonData = "[{"name":"Michael","age":20},{"name":"Mike","age":21}]"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = (Button)findViewById(R.id.buttonId); button.setOnClickListener(new ButtonListener()); } private class ButtonListener implements OnClickListener{ @Override public void onClick(View v) { JsonUtils jsonUtils = new JsonUtils(); jsonUtils.getObjectsFromJson(jsonData); } } public class JsonUtils { public void getObjectsFromJson(String jsonData) { Type listType = new TypeToken<LinkedList<User>>(){}.getType(); Gson gson = new Gson(); LinkedList<User> users = gson.fromJson(jsonData, listType); for(Iterator it = users.iterator() ; it.hasNext() ; ) { User user = (User) it.next(); System.out.println(user); } } } public class User { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "User [name=" + name + ", age=" + age + "]"; } } }