如何让Gson使用自定义字段名称将JSON转换为POJO

时间:2015-11-25 07:12:24

标签: java json gson pojo

我最近开始使用GSON,我正在解决这个json反序列化的问题。问题出在json元素下面,其中包含字段名称中的空格

{
longDescriptionNonHTML: {
What it is:: " An oil-free, color-tinted moisturizer."
What it does:: " This lightweight foundation can be reapplied as necessary and offers moisturizing, oil-control coverage for sensitive or acne prone skin."
}

    {
SKUType: "restricted"
brandName: "Laura Mercier"
brandId: 5809
skuID: "1228139"
availableInStore: 0
topSellerRank: 8297
productName: "Tinted Moisturizer - Oil Free"
shade_description: "Porcelain"
shortDescription: "What it is: An oil-free, color-tinted moisturizer.What it does: This lightweight foundation can be reapplied as necessary and offers moisturizing, oil-control coverage for sensitive or acne prone skin."
size: "1.7 oz"
listPrice: 0
salePrice: 0
image: "http://www.sephora.com/productimages/sku/s1228139-main-hero.jpg"
rating_product: 4.3
online_store: "http://www.sephora.com/tinted-moisturizer-oil-free-P310929?skuId=1228139&lang=en"
imageBrand: "http://www.sephora.com/contentimages/brands/lauramercier/5809_logo_279.png"
productId: "P310929"
formulation: "Liquid"
spf: ""
coverage: "Sheer, Medium"
finish: "Matte, Natural"
ingredients: "Vitamin C"
skintype: "Combination, Normal, Oily"
longDescription: "<b>What it is:</b><br> An oil-free, color-tinted moisturizer.<br><br><b>What it does:</b><br> This lightweight foundation can be reapplied as necessary and offers moisturizing, oil-control coverage for sensitive or acne prone skin."
longDescriptionNonHTML: {
What it is:: " An oil-free, color-tinted moisturizer."
What it does:: " This lightweight foundation can be reapplied as necessary and offers moisturizing, oil-control coverage for sensitive or acne prone skin."
}-
skintone: "2Y03"
longIngredientsDesc: ""
language: "en"
isPrimarySkintone: 1
isDefaultSku: 0
storeonly: 0
}

我在下面写了POJO

公共类LongDescriptionNonHTML {

@SerializedName("What it is:")
private String whatItIs;
@SerializedName("What it does:")
private String whatItDoes;

public LongDescriptionNonHTML(String a,String b){
    whatItDoes=a;
    whatItDoes=b;
}

public String getWhatItIs() {
    return whatItIs;
}

public void setWhatItIs(String whatItIs) {
    this.whatItIs = whatItIs;
}

public String getWhatItDoes() {
    return whatItDoes;
}

public void setWhatItDoes(String whatItDoes) {
    this.whatItDoes = whatItDoes;
}

}

另外,为了反序列化,我在下面写了代码

Gson gson = new GsonBuilder().setPrettyPrinting().create();
        JsonReader reader = new JsonReader(new FileReader(fileName));
        LongDescriptionNonHTML obj=gson.fromJson(reader, LongDescriptionNonHTML.class);
        System.out.println(obj.getWhatItDoes());

但它正在打印空值。

3 个答案:

答案 0 :(得分:1)

将JSON转换为POJO类可能很有用。

public static <T> T convertJSON2POJOClass(String json, Class<T> type) 
        {
            GsonBuilder gsonBuilder = new GsonBuilder();
            gsonBuilder.serializeNulls();

            try{
                return (T) gson.fromJson(json, type);
            } catch (Exception expJSONToClassConvertor) {
                baseDAO.getInstance().logAnError("common", baseDAO.getInstance().stackTraceToString(expJSONToClassConvertor));
                return null;
            }

答案 1 :(得分:0)

如果您发布的是实际的JSON和您的整个实际POJO代码,那么您的JSON和POJO结构之间就不匹配了:

  • 您要求Gson从您的JSON中生成LongDescriptionNonHTML
  • 但是你的JSON不只是 - 它实际上是包含 LongDescriptionNonHTML作为键longDescriptionNonHTML的值的其他对象。

答案 2 :(得分:0)

我解决了它

公共类LongDescriptionNonHTML {

//@SerializedName("What it is:")
private String whatItIs;
//@SerializedName("What it does:")
private String whatItDoes;

public LongDescriptionNonHTML(String a,String b){
    whatItDoes=a;
    whatItDoes=b;
}

public String getWhatItIs() {
    return whatItIs;
}

public void setWhatItIs(String whatItIs) {
    this.whatItIs = whatItIs;
}

public String getWhatItDoes() {
    return whatItDoes;
}

public void setWhatItDoes(String whatItDoes) {
    this.whatItDoes = whatItDoes;
}

然后创建了一个反序列化器

public class FooDeserializer实现了JsonDeserializer {

@Override
public LongDescriptionNonHTML deserialize(JsonElement json, Type typeOfT,
        JsonDeserializationContext context)
                throws JsonParseException {
    JsonObject jo = (JsonObject)json;
    String a =jo.get("What it is:").getAsString();
    String b =jo.get("What it does:").getAsString();
    return new LongDescriptionNonHTML(a,b);
}

}

然后最后测试了它 公共课jsonTest {

@Test
public void testJson() throws FileNotFoundException{
    String fileName="/Users/User/Documents/workspace/simulator/book.json";
    Gson gson = new GsonBuilder().setPrettyPrinting().registerTypeAdapter(LongDescriptionNonHTML.class, new FooDeserializer()).create();
    JsonReader reader = new JsonReader(new FileReader(fileName));
    LongDescriptionNonHTML obj=gson.fromJson(reader, LongDescriptionNonHTML.class);
    System.out.println(obj.getWhatItDoes());
}

}