简体   繁体   English

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

[英]How to Gson to convert JSON to POJO with custom field names

I recently started using GSON and i am facing an issue in deserialising this json. 我最近开始使用GSON,并且在反序列化此json时遇到问题。 The issue is at below json element which contains spaces in field names 问题在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
}

I wrote below POJO 我在下面写了POJO

public class LongDescriptionNonHTML { 公共类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;
}

} }

Also for deserialise it I wrote below code 同样为了反序列化,我在下面的代码中编写了代码

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());

But it is printing null value. 但是它正在打印空值。

It may be useful for you to convert JSON to POJO Class. 将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;
            }

If what you posted is the actual JSON and your whole actual POJO code then you have a mismatch between your JSON and POJO structure: 如果您发布的是实际的JSON和整个实际的POJO代码,那么JSON和POJO结构之间将不匹配:

  • You are asking Gson to produce a LongDescriptionNonHTML from your JSON. 您要Gson从JSON生成LongDescriptionNonHTML
  • But your JSON is not just that - it actually is some other object that contains a LongDescriptionNonHTML as the value for the key longDescriptionNonHTML . 但是您的JSON不仅如此-实际上,它是另一个包含 LongDescriptionNonHTML作为键longDescriptionNonHTML值的longDescriptionNonHTML

I solved it 我解决了

public class LongDescriptionNonHTML { 公共类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;
}

Then created a deserializer 然后创建了一个反序列化器

public class FooDeserializer implements JsonDeserializer{ 公共类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);
}

} }

and then finally tested it public class jsonTest { 然后最终对其进行了测试公共类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());
}

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM