Gson - Json字符串到pojo列表

时间:2016-12-17 17:08:46

标签: java gson

我有这个JSON响应,我希望使用Gson将其转换为等效的pojo对象列表。

{
 "title" : "Java Generics and Collections",
 "formattedPrice" : "INR 460.00",
 "source" : "abc"
}, 

{
 "title" : "Java Generics and Collections",
 "formattedPrice" : "INR 460.00",
 "source" : "xyz"
}

Product.java

public class Product {

   private String title;

   private String formattedPrice;

   private String source;

   //Getters and setters

 }

这可能是非常基本但我无法弄清楚。

2 个答案:

答案 0 :(得分:-1)

您可以这样做:

Gson gson = new Gson();
List<Product> products = gson.fromJson(jsonString, new TypeToken<List<Product>>(){}.getType());

但是你必须像Jason一样构建Json,请参阅下面的内容:

[
    {
        "title" : "Java Generics and Collections",
        "formattedPrice" : "INR 460.00",
        "source" : "abc"
    }, 
    {
        "title" : "Java Generics and Collections",
        "formattedPrice" : "INR 460.00",
        "source" : "xyz"
    }
]

您可以使用此site来验证您的json。

答案 1 :(得分:-1)

这来自Gson User Guide

假设JSON是一个有效数组(你给出的JSON缺少方括号):

[
    {
     "title" : "Java Generics and Collections",
     "formattedPrice" : "INR 460.00",
     "source" : "abc"
    }, 

    {
     "title" : "Java Generics and Collections",
     "formattedPrice" : "INR 460.00",
     "source" : "xyz"
    }
]

然后你可以这样做:

Type collectionType = new TypeToken<Collection<Product>>(){}.getType();
Collection<Product> productCollection = gson.fromJson(json, collectionType);

System.out.println("RESULTS: "+productCollection.toString());

以下是我使用的Product课程:

public class Product {

    private String title;

    private String formattedPrice;

    private String source;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getFormattedPrice() {
        return formattedPrice;
    }

    public void setFormattedPrice(String formattedPrice) {
        this.formattedPrice = formattedPrice;
    }

    public String getSource() {
        return source;
    }

    public void setSource(String source) {
        this.source = source;
    }

    @Override
    public String toString() {
        return "Product [title=" + title + ", formattedPrice=" + formattedPrice
                + ", source=" + source + "]";
    }

}

输出结果为:

RESULTS: [Product [title=Java Generics and Collections, formattedPrice=INR 460.00, source=abc], Product [title=Java Generics and Collections, formattedPrice=INR 460.00, source=xyz]]