gson parse items from comma-separated-value string within a json value

我怕爱的太早我们不能终老 提交于 2019-12-25 16:42:37

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!