Deserialize with gson and null values

前端 未结 2 1855
情歌与酒
情歌与酒 2020-12-05 07:35

I am trying to deserialize my own class with a null value. But my code doesn\'t work.

My json:

{\"Text\":null,\"Code\":0,\"Title\":\"This is Sparta!\         


        
2条回答
  •  一向
    一向 (楼主)
    2020-12-05 08:14

    I had a similar problem (an exception thrown on null value) with the following POJO:

    public class MyElement {
        private String something;
        private String somethingElse;
        private JsonObject subEntry; // this doesn't allow deserialization of `null`!
    }
    

    and this code:

    parsedJson = gson.fromJson(json, MyElement.class)
    

    when subEntry returned by the backend was null.

    I fixed it by changing the type of subEntry from JsonObject to JsonElement which is a parent class of both JsonObject and JsonNull, to allow deserialization of null values.

    public class MyElement {
        private String something;
        private String somethingElse;
        private JsonElement subEntry; // this allows deserialization of `null`
    }
    

    To later check for null at runtime, you'd do as follows:

    if (parsedJson.subEntry instanceof JsonNull) {
        ...
    } else {
        ...
    }
    

提交回复
热议问题