gson解析json_Json与Gson之简单对象转化和带泛型的List转化

时间:2020-10-16  来源:Google  阅读:


Gson 是 Google 提供的用来在 Java 对象和 JSON 数据之间进行映射的 Java 类库。可以将一个 JSON 字符串转成一个 Java 对象,或者反过来。在Android Studio中直接引用

compile "com.google.code.gson:gson:2.2.4"
下面先看一下怎么转化对象:

实体类如下:

public class TestEneity {
 
    /**
     * image : image/mango_cover.jpg
     * content : 火爆进口马来西亚特产大金芒果包邮500G
     * price : 18.9
     * PreferentialPrice : 14.9
     * you : 免邮费
     * number : 23
     */
 
    private String image;
    private String content;
    private String price;
    private String PreferentialPrice;
    private String you;
    private String number;
 
    public String getImage() {
        return image;
    }
 
    public void setImage(String image) {
        this.image = image;
    }
 
    public String getContent() {
        return content;
    }
 
    public void setContent(String content) {
        this.content = content;
    }
 
    public String getPrice() {
        return price;
    }
 
    public void setPrice(String price) {
        this.price = price;
    }
 
    public String getPreferentialPrice() {
        return PreferentialPrice;
    }
 
    public void setPreferentialPrice(String PreferentialPrice) {
        this.PreferentialPrice = PreferentialPrice;
    }
 
    public String getYou() {
        return you;
    }
 
    public void setYou(String you) {
        this.you = you;
    }
 
    public String getNumber() {
        return number;
    }
 
    public void setNumber(String number) {
        this.number = number;
    }
}

使用方式:


TestEneity testEntity=new TestEneity();
testEntity.setImage("image/mango_cover.jpg");
testEntity.setContent("火爆进口马来西亚特产大金芒果包邮500G");
testEntity.setPrice("18.9");
testEntity.setPreferentialPrice("14.9");
testEntity.setYou("免");
testEntity.setNumber("23");
 
System.out.println("----------简单对象之间的转化-------------");
// 简单的bean转为json
Gson gson=new Gson();
String s1 = gson.toJson(testEntity);
System.out.println("简单Bean转化为Json===" + s1);
 
// json转为简单Bean
TestEneity tset = gson.fromJson(s1, TestEneity.class);
System.out.println("Json转为简单Bean===" + tset);

List<TestEneity> testEntityList=new ArrayList<>();
for(int i=0;i<3;i++){
TestEneity testEntity=new TestEneity();
testEntity.setImage("image/mango_cover.jpg");
testEntity.setContent("火爆进口马来西亚特产大金芒果包邮500G");
testEntity.setPrice("18.9");
testEntity.setPreferentialPrice("14.9");
testEntity.setYou("免");
testEntity.setNumber("23");
testEntityList.add(testEntity);
System.out.println("----------带泛型的List之间的转化-------------");
// 带泛型的list转化为json
Gson gson=new Gson();
String s2 = gson.toJson(testEntityList);
System.out.println("带泛型的list转化为json==" + s2);
 
// json转为带泛型的list
List<TestEneity> retList = gson.fromJson(s2,
new TypeToken<List<TestEneity>>() {
}.getType());
for (TestEneity stu : retList) {
System.out.println(stu);
}
}

gson解析json_Json与Gson之简单对象转化和带泛型的List转化

http://m.bbyears.com/seo/104922.html

推荐访问:gson解析json数组
相关阅读 猜你喜欢
本类排行 本类最新