0

In my current android project, the API provides every JSON value in quotes:

{
  "id":"1234",
  "title":"Matrix",
  "subTitle":"",
  "year":"1999",
  "rating":"9"
}

I can successfully map this to my model (Obviously Integers are recognized by GSON?).

int id;
String title;
String subtitle;
int year;
int rating;

The problem occurs, when a movie has no rating. In this case the API returns
"rating":""
GSON isn't able to map that to an int.

How can I convince GSON to replace "" with -1 just for Integers, since I want to keep empty Strings e.g. for non-existent subtitles?

TypeAdapter seems to be what I need, but wouldn't it replace every empty String (even the ones mapping to a String)?

A2i_
  • 398
  • 3
  • 13
  • You could write a custom de-serializer. It sucks to have to do that for just one field, but that would solve your problem. Maybe someone more GSON-knowledgeable has a better solution though. – Mena Jul 08 '15 at 14:14
  • You'll have to write a custom deserializer - see official docs, https://sites.google.com/site/gson/gson-user-guide#TOC-Writing-a-Deserializer or this answer here http://stackoverflow.com/questions/16590377/custom-json-deserializer-using-gson – Zain Jul 08 '15 at 14:15
  • 1
    imo you should stick with the type the backend sends. – Blackbelt Jul 08 '15 at 14:17
  • Why not catch rating like String and parse to Integer if string is not empty? If is empty, replace with a custom string value. – Santiago Jul 08 '15 at 14:22

1 Answers1

0

I would do the modeling like this:

int id;
String title;
String subtitle;
// Here you have to be sure that year is always going to be a valid int
int year;
private String rating;

public int getRating() {
    return TextUtils.isEmpty(rating) ? -1 : Integer.parseInt(rating);
}

Of course, if your model is also sent back to your server, you need to adapt accordingly.

njzk2
  • 38,969
  • 7
  • 69
  • 107