我如何使用Gson Java解析此转义的Json? [英] How do I parse this escaped Json with Gson java?

查看:173
本文介绍了我如何使用Gson Java解析此转义的Json?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我收到以下无法控制的响应:

So I'm getting responses like the following which I have no control over:

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

乍一看,这似乎很简单,但是parameters元素需要作为json对象读取,我一生无法解决如何做到这一点.这是我目前正在尝试的方法:

At a glance it seems simple, but the parameters element needs to be read as a json object and I cannot for the life of me work out how to do it. This is what I am trying at the moment:

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 $

数据在哪里(通常是从服务器提取的):

Where data is (typically this is pulled from a server):

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

这肯定不是一个难题吗?

Surely this is not a difficult problem?

推荐答案

这里有什么

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

是一个JSON对,其中名称(始终为JSON字符串)和值均为JSON字符串.该值为字符串,可以解释为JSON对象.就是这样

is a JSON pair where both the name (which is always a JSON string) and the value are JSON strings. The value is a String that can be interpreted as a JSON object. So do just that

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


以下


The following

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

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

这篇关于我如何使用Gson Java解析此转义的Json?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆