[英]Parse JsonString to JsonObject in Java
I have the following String : 我有以下字符串:
{
"response": true,
"model_original_id": "5acea0b5:1431fde5d6e:-7fff",
"model_new_id": 500568,
"model_new_version": 1,
"reload": true,
"idsModelProperties": [{
"key": "creation_date",
"value": "2013-12-23"
},
{
"key": "state",
"value": 1,
"displayValue": "Analisi"
}],
"idsNodes": [],
"idsConnectors": [],
"idsNodesProperties": []
}
and i need to parse it as a JSONObject. 我需要将其解析为JSONObject。 I tried to use quickjson but it gives me an exception when it tries to parse an emty string .
我试图使用quickjson但它在尝试解析一个emty字符串时给了我一个例外。 This is what i tried :
这是我试过的:
JsonParserFactory factory=JsonParserFactory.getInstance();
JSONParser parser=factory.newJsonParser();
Map jsonData=parser.parseJson(response_output);
Exception: Exception in thread "main" com.json.exceptions.JSONParsingException: @Key-Hierarchy::root/idsNodes[0]/ @Key:: Value is expected but found empty...@Position::256 异常: 线程“main”中的异常com.json.exceptions.JSONParsingException:@ Key-Hierarchy :: root / idsNodes [0] / @Key ::值是预期的,但是找到空... @ Position :: 256
Any idea? 任何的想法?
I'll give you an alternative since it looks like quick-json
has trouble parsing empty json arrays. 我会给你一个替代方案,因为它看起来像
quick-json
在解析空的json数组时遇到了麻烦。 Check out Gson
. 看看
Gson
。
String json = "{ \"response\": true, \"model_original_id\": \"5acea0b5:1431fde5d6e:-7fff\", \"model_new_id\": 500568, \"model_new_version\": 1, \"reload\": true, \"idsModelProperties\": [{ \"key\": \"creation_date\", \"value\": \"2013-12-23\" }, { \"key\": \"state\", \"value\": 1, \"displayValue\": \"Analisi\" }], \"idsNodes\": [], \"idsConnectors\": [], \"idsNodesProperties\": []}";
JsonParser jsonParser = new JsonParser();
JsonElement jsonElement = jsonParser.parse(json);
JsonElement
is an abstract class. JsonElement
是一个抽象类。 Its sub types are JsonArray
, JsonNull
, JsonObject
and JsonPrimitive
. 它的子类型是
JsonArray
, JsonNull
, JsonObject
和JsonPrimitive
。 In the example above, the actual instance is a JsonObject
because your json String
is a json object. 在上面的示例中,实际的实例是
JsonObject
因为您的json String
是一个json对象。 It internally contains a LinkedTreeMap
but you don't really need access to it. 它内部包含一个
LinkedTreeMap
但您实际上并不需要访问它。 You can access the different json objects directly on the JsonElement
. 您可以直接在
JsonElement
上访问不同的json对象。
While the author of the question has already accepted an answer, someone else might be searching for the same issue. 虽然问题的作者已经接受了答案,但其他人可能正在搜索相同的问题。 I've fixed the issues I know of with quick-json in https://code.google.com/p/quick-json/issues/detail?id=11
我在https://code.google.com/p/quick-json/issues/detail?id=11中使用quick-json解决了我所知道的问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.