如何通过Gson java传递这个转义的Json?

时间:2015-12-23 01:39:30

标签: java json gson

所以我得到的回复如下,我无法控制:

{
    "message": "someName someLastName has sent you a question",
    "parameters": "{\"firstName\":\"someName\",\"lastName\":\"someLastName\"}",
    "id": 141
}

一目了然看起来很简单,但是参数元素需要作为json对象读取,我不能为我的生活找出如何做到这一点。这就是我现在正在尝试的事情:

JsonObject parameters = data.getAsJsonObject().get("parameters").getAsJsonObject();
/throws java.lang.IllegalStateException: Not a JSON Object: "{\"firstName\":\"someName\",\"lastName\":\"someLastName\"}"

所以我试过了:

String elementToString = data.getAsJsonObject().get("parameters").toString().replace("\\\"", "\"");
JsonObject parameters = new Gson().fromJson(elementToString, JsonElement.class).getAsJsonObject();
//throws com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 5 path $

数据的位置(通常是从服务器提取的):

JsonElement data = new Gson().fromJson("  {\n" +
        "    \"message\": \"someName someLastName has sent you a question\",\n" +
        "    \"parameters\": \"{\\\"firstName\\\":\\\"someName\\\",\\\"lastName\\\":\\\"someLastName\\\"}\",\n" +
        "    \"id\": 141\n" +
        "  }", JsonElement.class);

当然这不是一个难题吗?

2 个答案:

答案 0 :(得分:11)

你在这里有什么

"parameters": "{\"firstName\":\"someName\",\"lastName\":\"someLastName\"}",

是一个JSON对,其中名称(始终是JSON字符串)和值都是JSON字符串。该值是一个可以解释为JSON对象的String。那就是那个

String jsonString = data.getAsJsonObject().get("parameters").getAsJsonPrimitive().getAsString(); 
JsonObject parameters = gson.fromJson(jsonString, JsonObject.class);

以下

Gson gson = new Gson();
JsonElement data = gson
        .fromJson("  {\n" + "    \"message\": \"someName someLastName has sent you a question\",\n"
                + "    \"parameters\": \"{\\\"firstName\\\":\\\"someName\\\",\\\"lastName\\\":\\\"someLastName\\\"}\",\n"
                + "    \"id\": 141\n" + "  }", JsonElement.class);
String jsonString = data.getAsJsonObject().get("parameters").getAsJsonPrimitive().getAsString(); 
JsonObject parameters = gson.fromJson(jsonString, JsonObject.class);
System.out.println(parameters);

打印JsonObject

的JSON文本表示
{"firstName":"someName","lastName":"someLastName"}

答案 1 :(得分:0)

我用于获取具体对象(无论它已经是对象还是转义字符串)的解决方案是这样的反序列化器:

public class MyDeserializer implements JsonDeserializer<MyThing> {

    @Override
    public MyThing deserialize(JsonElement element, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        if (element.isJsonObject()) {
            //Note Don't use a gson that contains this deserializer or it will recurse forever
            return new Gson().fromJson(element.getAsJsonObject(), MyThing.class);
        } else {
            String str = element.getAsJsonPrimitive().getAsString();
            return gson.get().fromJson(str, MyThing.class);
        }
    }    

}