所以我得到的答案如下,我无法控制:
{ "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);
当然这不是一个难题吗?
你在这里有什么
"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);
打印出的JSON文本表示 JsonObject
{"firstName":"someName","lastName":"someLastName"}