JsonDeserializer无法使用gson

时间:2018-02-20 11:08:51

标签: java gson

我有一个列表(列表包含requiredFields,这个列表可以从文本文件中获取动态数据),我有api响应jsonData。

现在,我需要从api(jsonData)响应中提取数据,只需要从必需的字段(包含字段的列表)中提取数据。所有这些都需要使用gson serializer

完成
 public class EDSJsonSerializer implements JsonDeserializer {

    final list<String>;  //  list can be populated by reading data from text 
 file

  //ex: list<Strin> is : [ab,bc]

     @Override
    public JsonElement deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {

        jsonElement => {"ab":"234234","bc":"wrwerewe","ww":"345fsd","456":"dfgdfg"}

        final Map map = new HahMap();

        map should contain only 2 elements {"ab":"234234","bc":"wrwerewe"}
        map can be populated with list above given as keys and values from json passed

    }
}


final String json = "";  // json is the api response string
 final GsonBuilder builder = new GsonBuilder();
        builder.registerTypeAdapter(Map.class, new EDSJsonSerializer());

        final Gson gson = builder.create();

        final String map =  gson.toJson(json);

    it is not working as expected and not throwing any error/exception.

请帮我解决这个问题

谢谢, Syamala。

1 个答案:

答案 0 :(得分:0)

首先,456不是有效的Java类字段名称。这可能是您遇到问题的一个原因,即使您可能永远也不会使用Json。

其次,您最好使用ExclusionStrategy来决定哪些字段取消&amp; amp;序列

在你的情况下:

@RequiredArgsConstructor
public class ExcludeUnlistedFields implements ExclusionStrategy {
    @NonNull
    private Set<String> fieldsToInclude;
    @Override
    public boolean shouldSkipField(FieldAttributes f) {
        // if you need to restrict to specific a class/classes
        // add the checks here also
        return ! fieldsToInclude.contains(f.getName());
    }
    @Override
    public boolean shouldSkipClass(Class<?> clazz) {
        return false;
    }
}

并使用它:

 Set<String> fieldsToInclude = new HashSet<>(Arrays.asList("ab", "bc"));
 ExclusionStrategy es = new ExcludeUnlistedFields(fieldsToInclude);        
 Gson gson = new GsonBuilder().setPrettyPrinting()
                              .addDeserializationExclusionStrategy(es).create();