Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse JsonString to JsonObject in Java

Tags:

java

json

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. I tried to use quickjson but it gives me an exception when it tries to parse an emty string . 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

Any idea?

like image 840
Blerta Dhimitri Avatar asked Dec 23 '13 15:12

Blerta Dhimitri


1 Answers

I'll give you an alternative since it looks like quick-json has trouble parsing empty json arrays. Check out 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. Its sub types are JsonArray, JsonNull, JsonObject and JsonPrimitive. In the example above, the actual instance is a JsonObject because your json String is a json object. It internally contains a LinkedTreeMap but you don't really need access to it. You can access the different json objects directly on the JsonElement.

like image 164
Sotirios Delimanolis Avatar answered Oct 02 '22 23:10

Sotirios Delimanolis