Reputation: 155
I am using Realm as database but it cannot save String Array directly.So, I have to convert it into custom object before save. That's why I am writing custom deserializer. However, I find that the deserializer didn't catch the json during debug. (But I change the String[].class to String.class, it catches "Peter")
Now my json from server is
{
"name":"Peter",
"role":[
"user",
"admin"
]
}
Code of registering deserializer for handling String Array:
Gson gson =
new GsonBuilder()
.registerTypeHierarchyAdapter(String[].class, new ListStringResponseDeserializer())
Upvotes: 0
Views: 499
Reputation: 2456
Your response is not an array of strings, it's an object containing an array of strings. You can deserialize it like this:
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
class Test {
class Root {
String name;
String[] role;
}
public static void main(String args[]) {
// JSON from question
String json = "{\n"+
"\n"+
" \"name\":\"Peter\",\n"+
" \"role\":[\n"+
"\n"+
" \"user\",\n"+
" \"admin\"\n"+
" ]\n"+
"}\n"+
"\n";
Gson gson = new GsonBuilder().create();
Root root = gson.fromJson(json, Root.class);
System.out.println(root.name);
for (String s: root.role) {
System.out.println(s);
}
}
}
Output
Peter
user
admin
Upvotes: 0
Reputation: 418
You can try using http://realmgenerator.eu - paste your JSON there and you will get your custom object to store strings (but you have to check the "use classes RealmInt and RealmString for primitive arrays" checkbox). Then create Gson object using GsonBuilder like here https://gist.github.com/jocollet/91d78da9f47922dc26d6
Upvotes: 1