ANDROID_MARS学习笔记_S02_015_Gson解析json串为对象集合
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ANDROID_MARS学习笔记_S02_015_Gson解析json串为对象集合相关的知识,希望对你有一定的参考价值。
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 + "]"; } } }
以上是关于ANDROID_MARS学习笔记_S02_015_Gson解析json串为对象集合的主要内容,如果未能解决你的问题,请参考以下文章
ANDROID_MARS学习笔记_S02_001_Spinner
ANDROID_MARS学习笔记_S02_004_ExpandableListActivity
ANDROID_MARS学习笔记_S02重置版_001_HanderLooperMessageThreadThreadLocal
ANDROID_MARS学习笔记_S02_005_AppWidget1