• 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 + "]";
            }
        }
    }
  • 相关阅读:
    hystrix总结之缓存
    python3列表
    hystrix总结之多返回值命令
    hystrix总结之限流
    hystrix(5) 延时检测
    redis-start
    设计模式-4建造者模式
    设计模式-3原型模式
    设计模式-2工厂设计模式
    设计模式-七大设计原则
  • 原文地址:https://www.cnblogs.com/shamgod/p/5202264.html
Copyright © 2020-2023  润新知