问题
I am parsing a json string using gson. It is similar to this:
{
"ACode": "aa",
"RCode": "rr",
"Errors": "e1,e2,e3"
}
I think that the errors should have been a proper json array, but I don't have control of that.
I want to get the errors into an array or collection in java. This is easy enough using String.split with comma as separator. However I am new to gson and I don't know if I would be ignoring functionality that it provides to parse a comma separated string.
Does anyone know whether gson can handle this automatically?
回答1:
I want to get the errors into an array or collection in java.
Try this one
String json = "{\"ACode\": \"aa\",\"RCode\": \"rr\", \"Errors\": \"e1,e2,e3\" }";
class ErrorsDeserializer implements JsonDeserializer<String[]> {
public String[] deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
return ((JsonObject) json).getAsJsonPrimitive("Errors").getAsString().split(",");
}
}
Gson gson1 = new GsonBuilder().registerTypeAdapter(String[].class, new ErrorsDeserializer())
.create();
String[] errors = gson1.fromJson(json, String[].class);
for (String error : errors) {
System.out.println(error);
}
回答2:
you can create a class with variables "ACode","RCode","Errors" then use gson to convert it to that class, CustomObject obj2 = gson.fromJson(json, CustomObject .class);
来源:https://stackoverflow.com/questions/23071765/gson-parse-items-from-comma-separated-value-string-within-a-json-value