0

I'd like to understand the difference with a server returning value verses that value being completely absent in the response.

lets take at what i have so far:

data class MyApiResponse(@SerializedName("name") val name: String,
                                  @SerializedName("address") val address: String,
                                  @SerializedName("max_time") val maxTime: Double? = null //this field  might  BE  COMPLETELY absent in response, what will  happen  here ? 
)

regarding the maxTime value, if the value is COMPLETELY absent from server response, will the app crash or will the value be null ?

the issue is im trying to distinguish between server sending

max_time: null vs it being completely absent ,how does gson handle this ?

j2emanue
  • 60,549
  • 65
  • 286
  • 456
  • I think it will just be null, I have a similar setup in my project where some fields are just sometimes not sent. They come as null in my POJOs. I use Java but it should be the same. Do you need to differentiate between those two states (do a different thing for null vs absent) or is it just a theoretical question? – Vucko Oct 04 '19 at 06:51
  • i dont need to do anything different. i just want to know if app will crash if value is ABSENT. – j2emanue Oct 04 '19 at 06:52
  • It will be null in absence of the value ,and can you do try catch block? that will be great. – raj kavadia Oct 04 '19 at 07:02

2 Answers2

1

In both cases it will be null. Might look here for more info: Gson optional and required fields

r2rek
  • 2,083
  • 13
  • 16
0

Please try this solution:

    String json = ""; //Your json has a String
    JsonObject jsonObject = new JsonParser().parse(json).getAsJsonObject();


    String name = jsonObject.get("name").toString();
    String adress = jsonObject.get("address").toString();
    //If null, use a default value
    JsonElement max_time = jsonObject.get("max_time");
    String text = (max_time instanceof JsonNull) ? "" : max_time.getAsString();




    String json = ""; //Your json has a String
    Gson gson = new GsonBuilder().serializeNulls().create();
    MyApiResponse myApiResponse = gson.fromJson(json, YOURCLASSNAME.class);
Himanshu
  • 141
  • 1
  • 3