I want to parse this json to retrieve the value of tel or user_id
For example:
{
"status":"ok",
"account":{
"0":{
"user_id":"2",
"thirdparty_id":"200",
"tel":"28000000",
"mobile":"28000000",
"fax":"28000000"
}
}
}
Here is the code I am attempting to use to retrieve tel:
JsonParser jp = new JsonParser();
JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent()));
JsonObject rootobj = root.getAsJsonObject();
JsonObject rootobj1 = (JsonObject) rootobj.get("account");
JsonObject rootobj2 = (JsonObject) rootobj.get("0");
String tel=rootobj2.get("tel").getAsString();
The problem is that a java.lang.NullPointerException is thrown at this line :
String tel=tel=rootobj2.get("tel").getAsString();
First thing if you have post the JsonString correctly then it is not a valid json as tel" should be "tel"
Then you can parse it using org.json as
JSONObject jsonObject = new JSONObject(str);
JSONObject json1 = new JSONObject(jsonObject.get("account").toString());
JSONObject json2 = new JSONObject(json1.get("0").toString());
System.out.println(json2.get("user_id").toString());
You have two problems. First, you are not actually descending the tree. Initialize rootobj2 like this:
JsonObject rootobj2 = (JsonObject) rootobj1.get("0"); // NOT rootobj.get("0");
Second, once rootobj2 is initialized correctly, it will not have an attribute "0". Try this:
String tel=rootobj2.get("tel").getAsString(); // NOT rootobj2.get("0").getAsString();
Related
I am kinda new to Rest assured testing, I have been dealing with diff. json and Api's.
I know how to pass a json object as body for POST request but my code gives error when I try to pass a JSON Array as body for POST request can someone suggest me how to do it.
The code I have been using for json object is
obj = parser.parse(new FileReader("path of json"));
jsonObject = (JSONObject) obj;
String jsonString = jsonObject.toJSONString();
Map<String, String> body = new ObjectMapper().readValue(jsonString, HashMap.class);
response = RestAssuredExtension.PostOpsWithBody(url, body);
This code gives class cast exception at
jsonObject = (JSONObject) obj; when I pass a json array.
Kindly help me with the same
This is the JSON Array
[
{
"findingId": "20177044",
"unsupressAfterDuration": 1669968369043,
"developer": "manan.girdhar#armorcode.io",
"kbIds": [],
"ticketConfigurationId": "3350",
"customFields": []
}
]
Your parser parses the part of JSON and probably returns a JSONArray, but you are casting it to JSONObject. Maybe you want to use something like
obj = parser.parse(new FileReader("path of json"));
if (obj instanceof JSONObject) {
jsonObject = (JSONObject) obj;
String jsonString = jsonObject.toJSONString();
Map<String, String> body = new ObjectMapper().readValue(jsonString, HashMap.class);
response = RestAssuredExtension.PostOpsWithBody(url, body);
} else {
throw new Exception("We do not know how to handle non-objects like " + obj.getClass().getName());
// replace this with list-handling code
}
If you want only one code fragment to handle both objects and lists, cast to JsonStructure.
answering my own question as I found a solution
JSONArray array1 = new JSONArray();
data1.put("findingId", findingIdFinal);
data1.put("unsupressAfterDuration", "1669968369043");
data1.put("developer","manan.girdhar#armorcode.io");
data1.put("kbIds",array1);
data1.put("ticketConfigurationId", jiraId);
data1.put("customFields",array1);
array.put(data1);
String jsonString = array.toString();
List<Map<String, String>> body = new ObjectMapper().readValue(jsonString, List.class);
response = RestAssuredExtension.PostOpsWithBodyWithArray(url, body);
I`m trying to fetch some values fron a JSON file using:
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("C:\\myfile.json"));
JSONArray array= new JSONArray();
array.add(obj);
If I run: System.out.println(array); , the output is
[{"flowrate":{"mod":0,"value":110},"command":{"cancel":0,"start":0}}]
, which is my json file.
My problem is how to get value from a specific field, let's say the value of "comand":"cancel".
I've tried JSONObject myitem = array.getJSONObject(1).getJSONObject("cancel"); with no success (error: getJSONObject(int) is undefined for the type JSONArray).
I mention that I'm using the json-simple toolkit.
I also could not validate your JSON. I made an assumption that you wanted to create an array of two objects (flowrate and command) and fixed the JSON:
String value = "[{\"flowrate\":{\"mod\":0,\"value\":110}},{\"command\":{\"cancel\":0,\"start\":0}}]";
JSONParser parser = new JSONParser();
Object obj = parser.parse(value);
JSONArray array=(JSONArray)obj;
JSONObject jo = (JSONObject) array.get(1);
System.out.println(jo.get("command"));
which gives the following output:
{"cancel":0,"start":0}
Process finished with exit code 0
After many hours of searching, I discovered that there is big difference between { } and [ ], therefore differnent methodes to parse them:
In my case:
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("C:\\myfile.json"));
JSONObject jsonObject = (JSONObject) json;
JSONObject command= (JSONObject) jsonObject.get("command");
System.out.println("command: " + command);
long cancel= (Long) command.get("cancel");
System.out.println("cancel: " + cancel);
Here you'll find the best example for nested json objects
I am trying to create a common parser in java.I am passing json object from different class based on my need.But parsing doesnot works for me.Can anybody help me to make a JSONObject parser in java.Any help will be highly appreciable....
This is my code for common parser
public JSONObject jsonParser(JSONObject objJson){
//JSONObject myjson = new JSONObject(objJson);
JSONArray the_json_array = objJson.getJSONArray("profiles");
JSONObject SnapshotRequest= objJson.g;
Iterator x = SnapshotRequest.keys();
JSONArray jsonArray = new JSONArray();
while (x.hasNext()){
String key = (String) x.next();
jsonArray.put(songs.get(key));
}
}
In this code I am getting an error that need to cast.
JSONArray the_json_array = objJson.getJSONArray("profiles");
But casting won't work.
Here is my json Object.
{"id":"mrbbt6f3fa99gld0m6n52osge0",
"name_value_list":
{"user_default_dateformat":{"name":"user_default_dateformat","value":"m/d/Y"}},
"module_name":"Users"}
I got id,and module_name through following code.How can i get user_default_dateformat?.
I know it may so simple but I am a newbie in json.
String jsonResponse;
while ((jsonResponse = br.readLine()) != null) {
jsonOutput = jsonResponse;
}
JSONObject job = new JSONObject(jsonOutput);
System.out.println(job);// i can see the same json object
that i showen above.
sessionID = job.get("id").toString();
Exception generating coge
JSONObject job2=new JSONObject(job);
dateFormat = job2.get("user_default_dateformat").toString();
The Eexception is
org.json.JSONException: JSONObject["user_default_dateformat"] not found.
Thanks,
name_value_list is also an Object.
JSONObject job2 = new JSONObject(job.get("name_value_list"));
So there you get
job2.get("user_default_dateformat");
Every {} in your JSON is an object. So for every String you get which is something like {"xy":"za","ab":"cd"} you have to cast it to the JSONObject
Edit for your error:
As you can see in your code the line:
JSONObject job2=new JSONObject(job);
will try to generate a JSONObject out of your JSONObject.
You have to get the JSONObject in your JSONObject.
You want to get the user_default_dateformat which is in your JSONObject:
String name_value_list_string = job.get("name_value_list").toString();
//this string is another json-string which contains the user_default_dateformat
JSONObject name_value_list_object = new JSONObject(name_value_list_string);
//This JSONObject contains the user_default_dateformat but this is also a JSONObject
String user_default_dateformat_string = name_value_list_object.get("user_default_dateformat").toString();
//this String contains the user_default_dateformat JSONString
JSONObject user_default_dateformat_object = new JSONObject(user_default_dateformat_string);
//This JSONObject contains the String values of your user_default_dateformat
if you are using JSONSimple library you can use this:
jsonObject = (JSONObject) new JSONParser().parse(jsonstr);
System.out.println((JSONObject)jsonObject.get("name_value_list"))).get("user_default_dateformat"));
This should give you the required result.
1) I've got a JSON file:
{
"serverURI":"http://localhost:8080/PocketUNI_API/serverURLs",
"newsURI":"http://localhost:8080/gateway/rss/rss.xml",
"modulesURI":"http://localhost:8080/PocketUNI_API/modules"
}
2) I need to get URLs on Java client in String format.
String json = jsonReceiver.makeHttpRequest(URL_SERVER, "GET", params);
JSONArray uris = new JSONArray(json);
Receiver works fine and json shows the correct string received, but when it goes to parsing with JSONArray it throws an error
org.json.JSONException: Value {"serverURI":"http:\/\/192.168.0.... of type org.json.JSONObject cannot be converted to JSONArray.
Question: How to parse json with URL values?
You don't get a JSONArray but a JSONObject.
JSONObject uris = new JSONObject(json);
json is a json object not an array, that is why you are getting the error. An array will be wrapped with in [ and ], and objects within { and }.
JSONObject uris = new JSONObject (json);
Instead of JSONArray you must use JSONObject.
JSONObject uris = new JSONObject(json);
In your code just replace JSONArray to JSONobject
JSONObject uris = new JSONObject(json);