GSON -JSON字符串到Pojo列表



我有这个json响应,我想使用gson。

{
 "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
 }

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

这来自GSON用户指南

假设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]]

您可以做这样的事情:

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

,但是您必须像列表一样构建JSON,请参阅Bellow:

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

您可以使用此站点来验证您的JSON。

最新更新