码迷,mamicode.com
首页 > 移动开发 > 详细

ANDROID_MARS学习笔记_S02_015_Gson解析json串为对象集合

时间:2016-02-20 00:25:09      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:

 

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串为对象集合

标签:

原文地址:http://www.cnblogs.com/shamgod/p/5202264.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!