Gson解析Json数据
在Android开发中就经经常使用到json解析。方便的是Google已经为我们提供了一个非常棒的json解析库–gson。
下面是演示样例代码:
/** * GSON解析JSON数据 * @author dream * */ public class TestGsonActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); /* //解析josn数据转换成对应对象 String jsonData = "{id:1, name=\"zhangsan\", sex=\"男\"}"; Person p = new Gson().fromJson(jsonData, Person.class); // TextView text = new TextView(this); text.setText(p.getId()+" "+ p.getName()+ " "+p.getSex()); */ //解析json数据转换成list String jsonData = "[{id:1, name=\"zhangsan\", sex=\"男\"}," + "{id:2, name=\"lisi\", sex=\"男\"}]"; List<Person> list = new Gson().fromJson(jsonData, new TypeToken<List<Person>>(){}.getType()); StringBuilder sd = new StringBuilder(); for(int t=0; t<list.size(); ++t){ sd.append(list.get(t)); } TextView text = new TextView(this); text.setText(sd.toString()); setContentView(text); } }
执行结果:
posted on 2017-05-22 17:47 yjbjingcha 阅读(126) 评论(0) 编辑 收藏 举报