I am using a ActiveAndroid to cache response from Retrofit network calls.
I made a class which looks like :-
class Article extends Model {
@Column(name = "title")
@SerializedName("title")
@Expose
public String title;
@Column(name = "authors")
@SerializedName("authors")
@Expose
private String authors;
}
The corresponding JSON is something like :-
{
"title":"Some title",
"authors": [{
"name": "Name",
"twitter":"@whatever"
}]
}
The sane way would be to use a has many relationship between Author
and Article
class, but authors are not being saved to database because they don't have @Expose
annotation (or even a variable) in the Article
class, and there is no way to have that annotation because has many calls will be a method call here which returns a List<Author>
.
// This will not work
@Expose
public List<Author> authors() {
return getMany(Author.class, "Article");
}
So the other way I thought was to store the JSON object in database as a string and serialize/deserialize for access.
That requires me to have the authors
variable a List<Author>
class, and provide a type serializer for it.
The problem with this approach is I have no way of knowing the Generic type being saved into the database. I can't return a List<Author>
type because just like authors, there are some more JSON Arrays in the whole of JSON.
So my the final solution that I have thought of is to store it as a string, treat it as a string and make a method to deserialize for access. Like this :-
private List<Author> _authors;
public List<Author> authors() {
if (_authors == null) {
Gson gson = ServiceGenerator.gsonBuilder.create();
Type type = new TypeToken<List<Author>>(){}.getType();
_authors = gson.fromJson(authors, type);
}
return _authors;
}
But when I try to do this, GSON throws an error :-
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_ARRAY
Basically saying that I am trying to treat a JSON array as a String.
So my question is how to treat some of the JSON Arrays as Strings with GSON converters.
My Retrofit Builder which I am using is :-
public static final GsonBuilder gsonBuilder = new GsonBuilder()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ss")
.excludeFieldsWithoutExposeAnnotation();
private static final Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl(API_BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gsonBuilder.create()));
Thanks for taking a look!
private List<Author> authors;
? – Blackbeltprivate String authors;
withprivate List<Author> authors
, and Author is correctly declared to reflect the content of your json, there is no reason why Gson shouldn't be able to parse it – Blackbelt