1

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?

upsert
  • 9
  • 4
Michael Stack
  • 365
  • 6
  • 12
  • 1
    I don't know of any functionality in gson to handle it automatically, but the best way to go about it would probably be to write a custom deserializer: http://stackoverflow.com/questions/6096940/how-do-i-write-a-custom-json-deserializer-for-gson – Mike B Apr 14 '14 at 23:01

2 Answers2

0

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);
}
Braj
  • 46,415
  • 5
  • 60
  • 76
  • For more info have a look at [Gson: Directly convert String to JsonObject (no POJO)](http://stackoverflow.com/questions/4110664/gson-directly-convert-string-to-jsonobject-no-pojo) – Braj Apr 14 '14 at 23:34
-1

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);