在GSON中将布尔值序列化为字符串Y或N

时间:2019-07-04 13:53:55

标签: android json gson

我已经尝试过使用这段代码将json序列化/反序列化为gson,反之亦然

public class BooleanSerializer implements JsonSerializer<Boolean>, JsonDeserializer<Boolean> {
    @Override
    public JsonElement serialize(Boolean src, Type typeOfSrc, JsonSerializationContext context) {
        return new JsonPrimitive(src?"Y":"N");
    }

    @Override
    public Boolean deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        return json.toString().equalsIgnoreCase("Y");
    }
}

并像这样使用此类

BooleanSerializer booleanSerializer = new BooleanSerializer();
        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.registerTypeAdapter(Boolean.class, booleanSerializer);
        gsonBuilder.registerTypeAdapter(Boolean.class, booleanSerializer);
        Gson gson = gsonBuilder.create();
Event event = gson.fromJson(eventJObj.toString(), Event.class);

模型类就是这样

public class Event implements Parcelable {
    private long eventID;
    private String objective;
    private String typeOfEvent;
    private Boolean isBookmarked;
    private Boolean iAttended;
    private Boolean isFeatured;
}

json格式是这样的

{
"eventID": 25,
"objective": "event",
"typeOfEvent": "conference",
"isBookmarked": "N",
"iAttended": "Y",
"isFeatured": "Y",
}

当我尝试将上述json转换为Event对象时,它未能将Y转换为true,它始终保持值为false。另外,出于某种原因,必须扩展Event对象的可包裹类。

我要去哪里错了?

1 个答案:

答案 0 :(得分:0)

我发现了错误。在deserialize类的BooeleanSerializer方法中,罪魁祸首。

public class BooleanSerializer implements JsonSerializer<Boolean>, JsonDeserializer<Boolean> {
    @Override
    public JsonElement serialize(Boolean src, Type typeOfSrc, JsonSerializationContext context) {
        return new JsonPrimitive(src?"Y":"N");
    }

    @Override
    public Boolean deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        // return json.toString().equalsIgnoreCase("Y"); // Wrong code
        return "Y".equalsIgnoreCase(json.getAsString()); 
       // json.getAsString() is the right way to get json element value
    }
}