I am working on a project with a SonicWall router. The responses that I get from it are in json format. I have no problems parsing them etc, etc but it seems that there is one case where the SW will return an invalid json as a response. Here is an example:
{
"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.
" }
]
}
]
}
Notice that the message does not close properly but changes a line? This causes the following 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)
Is there any way to turn this in a valid json?
Get the json response and replace all new lines first before parsing it to object.
response.replaceAll("\r?\n", "");
Sample code using 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"));
Output:
{"msg" : " Hello
World"}
Actual message: Hello World
Related
This question already has answers here:
How to remove an element from JSON string in Java?
(2 answers)
Closed 6 months ago.
I am trying to remove JSON array from a JSON file using org.json library
I am trying to remove webAutomation JSON array from the JSON file as follows
{
"instructor": "Test_Instructor",
"url": "www.google.com",
"services": "Test Automation Service",
"expertise": "Testing",
"linkedIn": "linkedIn",
"courses": {
"webAutomation": [
{
"price": "500",
"courseTitle": "Selenium"
},
{
"price": "333",
"courseTitle": "Protractor"
}
],
"apiAutomation": [
{
"price": "344.00",
"courseTitle": "Rest Assured API Automation"
}
],
"mobileAutomation": [
{
"price": "4555",
"courseTitle": "Appium"
}
]
}
}
I tried following code. Here str has JSON file
JSONObject jsonObject = new JSONObject(str);
jsonObject.getJSONObject("courses").getJSONArray("webAutomation");
System.out.println("after removal");
String str2 = mapper.writeValueAsString(jsonObject);
System.out.println(str2);
This is removing the whole JSON object instead of just JSON Array.
The output is {"empty":false}
Please help
You can use remove method in org.json.JSONObject#remove.
JSONObject json = new JSONObject(str);
json.getJSONObject("courses").remove("webAutomation");
System.out.println(json);
The output will be:
{
"instructor": "Test_Instructor",
"url": "www.google.com",
"services": "Test Automation Service",
"expertise": "Testing",
"linkedIn": "linkedIn",
"courses": {
"apiAutomation": [
{
"price": "344.00",
"courseTitle": "Rest Assured API Automation"
}
],
"mobileAutomation": [
{
"price": "4555",
"courseTitle": "Appium"
}
]
}
}
[
{
"sentence": "I want to buy shoes .",
"tree": {
"ROOT": [
{
"index": 2,
"token": "want",
"label": "VERB",
"pos": "VBP",
"tree": {
"nsubj": [
{
"index": 1,
"token": "I",
"label": "PRON",
"pos": "PRP"
}
],
"xcomp": [
{
"index": 4,
"token": "buy",
"label": "VERB",
"pos": "VB",
"tree": {
"aux": [
{
"index": 3,
"token": "to",
"label": "PRT",
"pos": "TO"
}
],
"dobj": [
{
"index": 5,
"token": "shoes",
"label": "NOUN",
"pos": "NNS"
}
]
}
}
],
"punct": [
{
"index": 6,
"token": ".",
"label": ".",
"pos": "."
}
]
}
}
]
}
}
]
This is tree represented in Json. But the keys for nested nodes keep changing.
For example "ROOT, nsubj, xcomp" ... etc.
How do I convert above json code to Java Object using gson.
Above response is from syntaxnet Parsey_Mcparseface api I'm trying to use.
Thanks in advance.
Gson has a method Gson#fromJson. For example, this is a code to read a simple String object.
Gson gson = new Gson();
String str = gson.fromJson("\"hello\"", String.class);
System.out.println("String: " + str);
You need to prepare Java Object to read your proposed JSON. But, you don't need to write code by yourself. There is a website providing automatical JSON object generator.
jsonschema2pojo
enter following items:
Target language: Java
Source type: JSON
Annotation type: Gson
and enter your class name, for example "ParsedSentence"
then, write code. You will get object.
Gson gson = new Gson();
ParsedSentence parsed = gson.fromJson(longLongJsonString, ParsedSentence.class);
I need to iterate and get the last values like name, url and color from below JSON response. Using java/gson api. Please help me on this.
{
"Title": {
"desc": [
{
"name": "PRE_DB",
"url": "http://jenkins.example.com/job/my_first_job/",
"color": "blue_anime"
},
{
"name": "SDD_Seller_Dashboard",
"url": "http://jenkins.example.com/job/my_second_job/",
"color": "blue_anime"
}
]
}
}
example output :
name : SDD_Seller_Dashboard
color :blue_anime
JSONObject data = new JSONObject(your_JSON_Repsonse);
JSONArray data_desc=data.getJSONArray(desc);
for(int i=0;i<=data_desc.length();i++)
{
name=data_desc.getString("name");
url=data_desc.getString("url");
color=data_desc.getString("color");
}
I am working with Android Studio, andI have a string variable, called sResponse (below). According to the debugger, it holds the following value:
{
"responseData": {
"emotion":"",
"lastinput":{actionResult={"value":{"label":"green","key":"1"},"result":"success","action":"displayClickableList"},
"answer":"Sorry, I did not understand.",
"link": {
"href":"",
"target":""
},
"extraData": {
},
"responseSession": {
"id":"c4a5ef257851a991eb32c69132c9",
"transaction":"4"
},
"responseDetails": "null",
"responseStatus": "200",
"applicationUrl": "http://noki-dev.cloud.com:90/moto-1/"
}
}
When I try to initialize a JSONObject with it with in this way:
jResponse=new JSONObject(sResponse);
...The following exception rises in my Logcat:
>>>>>>>>>Thread EXCEPTION1: Response with invalid JSON format: , FrontendActivity.java L:421 ***** *org.json.JSONException: Unterminated object at character 502 of : sResponse
I suspect that those // in the URL are causing trouble. I am no expert in escaping JSON Characters. How can I obtain a valid JSONObject from the previous string? What trouble can you spot in my approach?
Problem caused because of = sign near by actionResult as well as actionResult not surrounded with double quotes and you didn't close json string properly.
Replace Json String With:
{
"responseData": {
"emotion":"",
"lastinput":{"actionResult":{"value":{"label":"green","key":"1"},"result":"success","action":"displayClickableList"},
"answer":"Sorry, I did not understand.",
"link": {
"href":"",
"target":""
},
"extraData": {
},
"responseSession": {
"id":"c4a5ef257851a991eb32c69132c9",
"transaction":"4"
},
"responseDetails": "null",
"responseStatus": "200",
"applicationUrl": "http://noki-dev.cloud.com:90/role-va-1/"
}
}
}
and add } at the end of the string.
You can track the error using following online tool:
http://json.parser.online.fr/
You missed last closing curly at the end of the response.
Just add } on last line.
Corrected json Response
{
"responseData": {
"emotion": "",
"lastinput": {
actionResult: {
"value": {
"label": "green",
"key": "1"
},
"result": "success",
"action": "displayClickableList"
},
"answer": "Sorry, I did not understand.",
"link": {
"href": "",
"target": ""
},
"extraData": {
},
"responseSession": {
"id": "c4a5ef257851a991eb32c69132c9",
"transaction": "4"
},
"responseDetails": "null",
"responseStatus": "200",
"applicationUrl": "http://noki-dev.cloud.com:90/moto-1/"
}
}
}
I am trying to extract specific data from a json response using org.json.JSONObject library
Heres is my json response :
{
"facets": {
"application": [
{
"name": "38",
"distribution": 1
}
],
"node": [
{
"name": "frstlwardu03_05",
"distribution": 1
}
],
"area": [
{
"name": "x",
"distribution": 1
}
],
"company": [
{
"name": "war001",
"distribution": 1
}
]
},
"duObjects": [
{
"id": "TASK|TSK(ZRM760J)(000)(ZRM760JU00)(000)|ZSRPSRM000",
"name": "TSK(ZRM760J)(000)(ZRM760JU00)(000)",
"mu": "ZSRPSRM000",
"label": "",
"session": "ZRM760J|000",
"sessionLabel": "SAP SRM Achats frais generaux execution",
"uprocHeader": "ZRM760JU00|000",
"uprocHeaderLabel": "Header for SRM760J",
"uprocHeaderType": "CL_INT",
"domain": "M",
"domainLabel": "",
"application": "38",
"applicationLabel": "magasin",
"highlightResult": {
"name": "name",
"word": "TSK"
}
}
],
"totalCount": 1,
"pageSize": 10,
"pageCurrent": 1,
"pageNb": 1
}
Here is the method I used to convert the URL call to a jsonobject :
public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException
{
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-
8")));
String jsonText = readAll(rd);
JSONObject json = new JSONObject(jsonText);
return json;
} finally {
is.close();
}
}
When I call this method I am able to get the data in teh Duobject :
public static void main(String[] args) throws IOException, JSONException {
JSONObject json = readJsonFromUrl("http://frstmwarwebsrv.orsyptst.com:9000/duobject?
searchString=TSK(ZRM760J)(000)(ZRM760JU00)
(000)&filterchecks=nameJob,nameWF,nameSWF,application,domain&p.index=0&p.size=10");
System.out.println(json.getJSONArray("duObjects"));
}
Is there anyway I can extract only the name field of the DuObjects?
You can use
System.out.println(json.getJSONArray("duObjects").getJSONObject(0).getString("name"));
to get the name.
1 : your complete response is a JSON OBJECT
2 : if any element is written like
"some key name " : { " some value " }
this is a JSON Object
3 : if any element is writen like
"some key name " : " some value "
this is value inside you json object which you can get by
jsonObject.getString("key name")
4 : if any element is writen like
"some key name " : [ " some value " ]
then this is a JSON Array and you have to take it in to a JSON ARRAY and then traverse its elements by
jsonObject.getJSONARRAY("key name for JSON ARRAY IN RESPONSE ")
and then you can traverse the elements of the JSON ARRAY by
`jsonArrayObj.get(0);`
You can use Jackson libraries to covert to java. Jackson api provides annotation level and it automatically converts json to pojo object and object to json vice versa . refer this link. you can get good idea about this
http://wiki.fasterxml.com/JacksonSampleSimplePojoMapper
http://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson/