我正在使用SonicWall路由器开展项目。我从中得到的回答是json格式。我没有解析它们等问题,但似乎有一种情况,SW将返回一个无效的json作为响应。这是一个例子:
{
"success": false,
"reboot_required": false,
"status": [
{
"cli": [
{ "command": [ { "token": "no" }, { "token": "nat-policy" }, { "token": "id", "error": true }, { "token": "10", "error": true } ] },
{ "command": [ { "token": "end" } ] }
],
"info": [
{ "type": "error", "code": "CLI_E_NOT_FOUND", "message": "Nat Policy not found.
" }
]
}
]
}
请注意,邮件未正确关闭但更改了一行?这会导致以下parsingException:
Exception in thread "main" javax.json.stream.JsonParsingException: Unexpected char 13 at (line no=11, column no=97, offset=447)
at org.glassfish.json.JsonTokenizer.unexpectedChar(JsonTokenizer.java:532)
at org.glassfish.json.JsonTokenizer.readString(JsonTokenizer.java:189)
at org.glassfish.json.JsonTokenizer.nextToken(JsonTokenizer.java:376)
at org.glassfish.json.JsonParserImpl$ObjectContext.getNextEvent(JsonParserImpl.java:261)
at org.glassfish.json.JsonParserImpl$StateIterator.next(JsonParserImpl.java:172)
at org.glassfish.json.JsonParserImpl.next(JsonParserImpl.java:149)
at org.glassfish.json.JsonReaderImpl.readObject(JsonReaderImpl.java:177)
at org.glassfish.json.JsonReaderImpl.readArray(JsonReaderImpl.java:143)
at org.glassfish.json.JsonReaderImpl.readObject(JsonReaderImpl.java:180)
at org.glassfish.json.JsonReaderImpl.readArray(JsonReaderImpl.java:143)
at org.glassfish.json.JsonReaderImpl.readObject(JsonReaderImpl.java:180)
at org.glassfish.json.JsonReaderImpl.readObject(JsonReaderImpl.java:103)
有没有办法在有效的json中转换它?
答案 0 :(得分:3)
获取json响应并在将其解析为object之前先替换所有新行。
response.replaceAll("\r?\n", "");
使用GSON
API
String json = "{\"msg\" : \"Hello \n World\"}";
System.out.println(json);
json = json.replaceAll("\r?\n", "");
Map<String, String> map = new Gson().fromJson(json, new TypeToken<Map<String, String>>(){}.getType());
System.out.println("Actual message:" + map.get("msg"));
输出:
{"msg" : " Hello
World"}
Actual message: Hello World