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/
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"
}
]
}
}
I am trying to convert an Avro Kafka Event to Json and need to manipulate The Avro Event by Removing Strings from this Event.
I am using GSON Library to manipulate the Json String Object but somehow its not removing the intended String.
JsonElement je = new Gson().fromJson(matchRequest, JsonElement.class);
JsonObject jo = je.getAsJsonObject();
jo.remove("com.XXX.XXXX");
jo.remove("com.XXX.XXX");
jo.remove("com.XXX.XXX");
System.out.println("#################"+jo);
Json String I am Receiving as matchRequest is
{"interaction_id":"321","customer_id":"32","context_id":"123","work_id":"ewq","work_request_id":"213","task_type":"123","match_type":"wert","resource_list":{"com.xxx.xxxx":{"rank":1,"resource_data":{"com.xxx.xxxx":{"account_id":1,"source_name":"Mankind","channel_id":"voice"}}}},"service_list":{"com.xxx.xxxx":{"rank":5,"priority":1,"resource_count":"gvk","min_proficiency":"10","max_proficiency":"1","attributes":{"com.xxx.xxxx":{"category":"edw","value":"33232"}},"resource_offered":{"com.xxx.xxxx":{"agent_id":"rewq","account_id":"123","source_name":"wqe","resource_address":"ewq","source_address":"rewq","channel_id":"212","channel_provider":"wqe"}}}},"matching_state":"OFFERED"}
JSON Format
"interaction_id": "321",
"customer_id": "32",
"context_id": "123",
"work_id": "ewq",
"work_request_id": "213",
"task_type": "123",
"match_type": "wert",
"resource_list": {
"com.XXXXXX": {
"rank": 1,
"resource_data": {
"com.XXXX": {
"account_id": 1,
"source_name": "Mankind",
"channel_id": "voice"
}
}
}
},
"service_list": {
"com.XXXX": {
"rank": 5,
"priority": 1,
"resource_count": "gvk",
"min_proficiency": "10",
"max_proficiency": "1",
"attributes": {
"com.XXXX": {
"category": "edw",
"value": "33232"
}
},
"resource_offered": {
"com.XXXX": {
"agent_id": "rewq",
"account_id": "123",
"source_name": "wqe",
"resource_address": "ewq",
"source_address": "rewq",
"channel_id": "212",
"channel_provider": "wqe"
}
}
}
},
"matching_state": "OFFERED"
}
When you look at the documentation of the remove() method, it needs a key from the JSON object in parameter.
However, the JSON you are receiving does not contain "com.xxx.xxxx" as key, but some keys, like "resource_list", are linked to another JSON object containing "com.xxx.xxxx" as a key.
You may want to look recursively into the JSON object you receive to remove the intended String.
You need to perform your operation over your array:
jo.getAsJsonObject("resource_list").remove("com.XXX.XXXX");
This should do the trick.
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 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
At the moment i'm trying to understand json and how it works.
But i have a problem with an array of objects.
all objects in the array have a key called "value" (i know it's weird, it's not my code) what also is an object.
And now to the problem: This object called "value" has always different key-values.
So i dont now how i can parse the json code to java object code, when it differ, every time.
Here some examples:
First object of the array:
"value":
{
"local":
[
"English", "Deutsch", Espanol"
],
"english":
[
"English", "Deutsch", Espanol"
],
},
Second object(now a string, not object) of the array:
"value" : "",
Third object of the array:
"value" : {},
...
Maybe I'm doing the parsing wrong.
First I have created the beans classes in java for the json code and then I'm using the automatic parser of google. (gson)
It works when only one of the examples above is inside the json code. (it should not differ, like changing from string to object...)
Gson gson = new Gson();
Output output = gson.fromJson(json, Output.class);
Output is the main class for the json stuff.
I have found out that maybe while parsing I could check a value called "id" first, and from that I could create another beans class with the right variables ...
Thats the code i need to parse to java objects and how do you do that??
The problem is the key called "value", because its always different.
With my method of using the google parser "gson" it wont work, because i'm getting exception that its an string but i was waiting for an object...
{
"status":"success",
"data":{
"panel":{
"title":{
"label":{ "local":"Tote Selection", "english":"Tote Selection" },
"image":"public/img/pick.jpg", "type":"default"
},
"isFirst":false, // currently not used
"isLast":false, // currently not used
"ownCount":0, // currently not used
"panelsCount":0, // currently not used
"elements":[
{
"type":"text",
"id":"1", "value":{ "local":"Scan next order tote",
"english":"Scan next order tote" },
"label":{ "local":"", "english":"" }, "color":"000000",
"fontsize":18, "fontstyle":"flat", "alignment":"left",
"rows":"undefined", "bgcolor":"", "isFocus":false
},
{
"type":"text",
"id":"4", "value":{ "local":"Scan tote: ", "english":"Scan tote: " },
"label":{ "local":"", "english":"" }, "color":"000000", "fontsize":20,
"fontstyle":"strong", "alignment":"left", "rows":"undefined",
"bgcolor":"", "isFocus":false
},
{
"type":"input",
"id":"6", "value":"", "label":{ "local":"", "english":"" },
"color":"000000", "fontsize":24, "fontstyle":"flat", "alignment":"left",
"rows":"undefined", "isFocus":true
},
{
"type":"button",
"id":"1", "value":{ "local":"", "english":"" },
"label":{ "local":"Menu", "english":"Menu" }, "color":"000000",
"fontsize":14, "fontstyle":"strong", "alignment":"left",
"rows":"undefined", "isFocus":false
},
{
"type":"button",
"id":"4", "value":{ "local":"", "english":"" },
"label":{ "local":"Enter", "english":"Enter" }, "color":"000000",
"fontsize":14, "fontstyle":"strong", "alignment":"right",18
"rows":"undefined", "isFocus":false
}
]
},
"authToken":"0fdd440a-619f-4936-ab74-d189accb5bd9",
"routing":{
"controller":"panel",
"action":"process",
"workflowId":"singlepicking",
"taskId":"orderSelection"
}
}
}
Thank you for your help!
it looks a little bit different but your answer helped me! Thx
JsonParser parser = new JsonParser();
JsonObject obj = parser.parse(br).getAsJsonObject();
//now getting all the json values
String status = obj.get("status").getAsString();
JsonObject data = obj.getAsJsonObject("data");
String authToken = data.get("authToken").getAsString();
JsonObject routing = data.getAsJsonObject("routing");
String controller = routing.get("controller").getAsString();
String action = routing.get("action").getAsString();
String workflowId = routing.get("taskId").getAsString();
If I understood ur question properly u can retrieve the values of the JSONArray as below
for (int i = 0; i < JArray.length(); i++) {
print(JArray.getJSONObject(i).tostring())
}
So if i am right u are getting the JSON from a String First?? so please try below first store the String in JSONObject as JSONObject obj = new JSONObject(str);//str is the string that u are getting
to get the valueenglish that are in data-panel-tittle-label is
String englishinLable=obj .getJSONObject("data").getJSONObject("panel").getJSONObject("title").getJSONObject("label").optString("english")