Created
July 9, 2015 05:33
-
-
Save ar-android/08f6145b59c40c8182d5 to your computer and use it in GitHub Desktop.
Dezerialize gson custom
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class CategoryDezerializer implements JsonDeserializer<ListCategory> { | |
@Override | |
public ListCategory deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context) | |
throws JsonParseException { | |
final JsonObject jsonObject = json.getAsJsonObject(); | |
final JsonElement jsonID = jsonObject.get("ID"); | |
final JsonElement jsonTitle = jsonObject.get("title"); | |
final String title = jsonTitle.getAsString(); | |
final String id = jsonID.getAsString(); | |
final JsonObject jsonAuthorsArray = jsonObject.get("author") | |
.getAsJsonObject(); | |
final String authors = jsonAuthorsArray.get("username").toString(); | |
final ListCategory data = new ListCategory(); | |
data.setID(id); | |
data.setTitle(title); | |
data.setAuthor(authors); | |
return data; | |
} | |
} | |
// Configure Gson | |
GsonBuilder gsonBuilder = new GsonBuilder(); | |
gsonBuilder.registerTypeAdapter(ListCategory.class, new CategoryDezerializer()); | |
Gson gson = gsonBuilder.create(); | |
// Parse JSON to Java | |
ListCategory[] category = gson.fromJson(array.toString(), ListCategory[].class); | |
String author = category[0].getAuthor(); | |
String split = author.replaceAll("\"", ""); | |
System.out.println(split); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment