Last active
July 17, 2016 14:29
-
-
Save nshmura/cc58affeda0db60424cd0c1165a34d2a to your computer and use it in GitHub Desktop.
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
final GsonBuilder gsonBuilder = new GsonBuilder(); | |
gsonBuilder.registerTypeAdapter(PCategoryData.class, new PCategoryDataTypeAdapter()); | |
final Gson gson = gsonBuilder.create(); | |
String json = "{categories:[{value: \"\"}]}"; | |
PCityData pCityData = gson.fromJson(json, PCityData.class); | |
... | |
static class PCityData { | |
public List<PCategoryData> categories; | |
} | |
static class PCategoryData { | |
public double value; | |
} | |
public class PCategoryDataTypeAdapter extends TypeAdapter<PCategoryData> { | |
@Override | |
public PCategoryData read(JsonReader in) throws IOException { | |
final PCategoryData data = new PCategoryData(); | |
in.beginObject(); | |
while (in.hasNext()) { | |
switch (in.nextName()) { | |
case "value": | |
try { | |
data.value = Double.valueOf(in.nextString()); | |
} catch (NumberFormatException e) { | |
data.value = 0; | |
} | |
break; | |
} | |
} | |
in.endObject(); | |
return data; | |
} | |
@Override | |
public void write(JsonWriter out, PCategoryData data) throws IOException { | |
out.beginObject(); | |
out.name("value").value(data.value); | |
out.endObject(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment