首页 > 学院 > 开发设计 > 正文

AS GSON

2019-11-09 15:03:27
字体:
来源:转载
供稿:网友

方法一:

1.在Android Studio中按F4快捷键进入PRoject Structure

2点击+号

.

3.选择Library dependency

4.搜索GSON

5.添加进去

方法二:

在buil的.gradle中输入

compile 'com.google.code.gson:gson:2.6.2'——————————————————————————–

综上就会看到添加成功

—————————–

GsonFormat的安装

使用方法:

安装后重启android studio

然后在最上方code-Generate-GsonFormat

点OK就生成了

package com.example.myapplication;/** * Created by 小新 on 2016/3/24. */public class gson  {    /**     * name : 王五     * gender : man     * age : 15     * height : 140cm     */    private String name;    private String gender;    private int age;    private String height;    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getGender() {        return gender;    }    public void setGender(String gender) {        this.gender = gender;    }    public int getAge() {        return age;    }    public void setAge(int age) {        this.age = age;    }    public String getHeight() {        return height;    }    public void setHeight(String height) {        this.height = height;    }}

简单使用Demo

1.比如获取的Json数据是
String Data = "{students:[{name:'魏祝林',age:25},{name:'阿魏',age:26}],class:'三年二班'}  ";我们根据这个使用GsonFormat构建实体类
import com.google.gson.annotations.SerializedName;import java.util.List;/** * Created by 小新 on 2016/3/24. */public class bean {    /**     * students : [{"name":"魏祝林","age":25},{"name":"阿魏","age":26}]     * class : 三年二班     */    @SerializedName("class")    private String classX;    /**     * name : 魏祝林     * age : 25     */    private List<StudentsBean> students;    public String getClassX() {        return classX;    }    public void setClassX(String classX) {        this.classX = classX;    }    public List<StudentsBean> getStudents() {        return students;    }    public void setStudents(List<StudentsBean> students) {        this.students = students;    }    public static class StudentsBean {        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;        }    }}2.然后使用Gson解析数据
String Data = "{students:[{name:'魏祝林',age:25},{name:'阿魏',age:26}],class:'三年二班'}  ";Gson gson = new Gson();bean b = gson.fromJson(Data,bean.class);Log.v("Tag",b.getClassX());可以解析出他的班级是三年二班


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表