I'm fairly new to REST API calls in Java and I'm currently encountering problems with trying to get the "item" section from the JSON object (below). I guess it also confuses me that "response" is an object in an array too?/
The JSON file is below:
{
"version": "1.0",
"code": 200,
"request":{"text":["seafood" ], "lang": "en", "type": "stimulus"},
"response":[{
"text": "seafood",
"items":[
{"item": "Shrimp", "weight": 100, "pos": "noun" },
{"item": "Lobster",…
]
}]
}
I have currently managed to get the "response" part of the object using:
BufferedReader in = new BufferedReader(
new InputStreamReader(conection.getInputStream()));
StringBuffer json = new StringBuffer();
while ((readLine = in.readLine()) != null) {
json.append(readLine);
}
in.close();
JSONParser parser = new JSONParser();
try{
JSONObject object= (JSONObject) parser.parse(json.toString());
Object response = json.get("response");
...
Up to this point, I get stuck. I don't know what to do to 'response' to get to "items", and if I try to cast 'response' as a JSONObject, it will return as null?
What I want to try and do is to get each "item" in the "items" part and put it in a list.
Help would be very much appreciated!
I think it should works:
JSONParser parser = new JSONParser();
try{
JSONObject object= (JSONObject) parser.parse(json.toString());
JSONArray response = object.getJSONArray("response");
JSONObject responseObject = response.getJSONObject(0);
JSONArray expectedArray = responseObject.getJSONArray("items");
for (int i = 0; i < expectedArray.length(); i++) {
String item = expectedArray.getJSONObject(i).getString("item");
String weight = expectedArray.getJSONObject(i).getInt("weight");
......
//Here you can create your custom object and add to your array. For example
list.add(new MyOwnObject(item, weight));
}
....
Because response is array, not object
You should check the documentation for JSONObject. It describes all of the methods which are available. Note that there is no method named get(). Instead, you probably want to use getJSONArray()
Related
I'm trying to get a nested array from a json file, but I can't find a way to do it. What I want is a array with many other arrays. Using arr.toArray() I get a array with two strings one being "["user1", "name", "password"]" and "["user2", "name", "password"]". Is there a way to get an array with arrays?
{
"Users": {
"info": [
["user1", "name", "password"],
["user2", "name", "password"]
]
}
}
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("myPath"));
JSONObject jsonObject = (JSONObject) obj;
JSONObject jsonObject1 = (JSONObject) jsonObject.get("User1");
JSONArray arr = (JSONArray) jsonObject1.get("info");
System.out.println(arr.toArray());
} catch (Exception e) {
e.printStackTrace();
}
}
I think you might be using one of the older JSON Libraries, I believe its the org.json.simple library. If this is going to be an important project, I'd recommend switching over to the Google GSON Library.
For now, Try Switching
JSONObject jsonObject1 = (JSONObject) jsonObject.get("User1");
to
JSONObject jsonObject1 = (JSONObject) jsonObject.get("Users");
this should fix some of your problems. In your JSON file, Users is the object you need to get in order to access the info Array.
in the mean time, here's a starting place for GSON
GSON tutorialspoint
https://www.tutorialspoint.com/gson/gson_quick_guide.htm
I am trying to parse a JSON response in Java but am facing difficulty due to the response being array format, not object. I, first, referenced the this link but couldn't find a solution for parsing the JSON properly. Instead, I am receiving this error when trying to display the parsed data...
Exception in thread "main" org.json.JSONException: JSONObject["cardBackId"] not found.
Snippet for displaying data:
JSONObject obj = new JSONObject(response);
JSONArray cardBackId = (JSONArray) obj.get("cardBackId");
System.out.println(cardBackId);
Data response via Postman:
[
{
"cardBackId": "0",
"name": "Classic",
"description": "The only card back you'll ever need.",
"source": "startup",
"sourceDescription": "Default",
"enabled": true,
"img": "http://wow.zamimg.com/images/hearthstone/backs/original/Card_Back_Default.png",
"imgAnimated": "http://wow.zamimg.com/images/hearthstone/backs/animated/Card_Back_Default.gif",
"sortCategory": "1",
"sortOrder": "1",
"locale": "enUS"
},
While without JSONObject I am pulling the data fine in Java and verified by using response.toString in STDOUT, this is my first time using json library in Java and it is important I parse this data as json. Any advice with this is helpful.
The response is an array and not object itself, try this:
JSONObject obj = new JSONArray(response).getJSONObject(0);
String cardBackId = obj.getString("cardBackId");
Here is the output, along with relevant files used:
First parse the response as JsonArray, instead of JsonObject.
Get JsonObject by iterating through the array.
Now get the value using the key.
Look at this example using Gson library, where you need to define the Datatype to define how to parse the JSON.
The key part of the example is: Data[] data = gson.fromJson(json, Data[].class);
package foo.bar;
import com.google.gson.Gson;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
public class Main {
private class Data {
long cardBackId;
String name;
}
public static void main(String[] args) throws FileNotFoundException {
// reading the data from a file
BufferedReader reader = new BufferedReader(new FileReader("data.json"));
StringBuffer buffer = new StringBuffer();
reader.lines().forEach(line -> buffer.append(line));
String json = buffer.toString();
// parse the json array
Gson gson = new Gson();
Data[] data = gson.fromJson(json, Data[].class);
for (Data item : data) {
System.out.println("data=" + item.name);
}
}
}
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 getting an inputstream and converting it to String and then to JSONObject
Below is snippet for converting inputstream to String and then JSONObject.
But after converting to json object(line 6) I am getting only the first object instead of all the objects
Can you please let me know why I am getting only one object instead of all the n objects
InputStream in = new BufferedInputStream(conn.getInputStream());
String result = org.apache.commons.io.IOUtils.toString(in, "UTF-8");
int i =result.indexOf("{");
String forResult=result.substring(i);
System.out.println(forResult); // Result 1
JSONObject jsonObject = new JSONObject(forResult); // Line 6
System.out.println(jsonObject); // Result 2
After converting it to String it look like this
Result -1
{
"test_expr":"",
"val_expr":"someVale",
"val_advanced":true,
"machine_val":null
}, {...// n times}
Result-2 -only first object
{
"test_expr":"",
"val_expr":"someVale",
"val_advanced":true,
"machine_val":null
}
Thanks and please bear my ignorance as I am completly new in java
Because you json is not valid .There is a comma between JSONObject .
Change to this .
{
{
"test_expr":"",
"val_expr":"someVale",
"val_advanced":true,
"machine_val":null
},
{
"test_expr":"",
"val_expr":"someVale",
"val_advanced":true,
"machine_val":null
}
...
}
or
[
{
"test_expr":"",
"val_expr":"someVale",
"val_advanced":true,
"machine_val":null
},
{
"test_expr":"",
"val_expr":"someVale",
"val_advanced":true,
"machine_val":null
}
...
]
The source of JSONObject
/**
* Creates a new {#code JSONObject} with name/value mappings from the JSON
* string.
*
* #param json a JSON-encoded string containing an object.
* #throws JSONException if the parse fails or doesn't yield a {#code
* JSONObject}.
*/
public JSONObject(String json) throws JSONException {
this(new JSONTokener(json));
}
So a JSON-encoded string containing an object(like {}).
// make sure that you result contain {}
result = "{your data here}"
JSONObject json_data = new JSONObject(result);
And if you use JSONArray ,you should contain [] in your JSON
result = "[json data]";
JSONArray jsonArray = new JSONArray(result);
Well, concatenation of multiple jsons is not a valid json. Your parsing library should have rejected such an input, but it seems that it just stopped at the end of the valid object.
You can wrap the list it into an array: [{...},{...},{...}]. Then the parser will be able to correctly interpret it as an array.
I guess you are getting JSONArray object instead of JSONObject. Why do you need to get sub string of the result? Json array can start with [. See the difference between JSONObject and JSONArray. Difference between JSONObject and JSONArray
Thanks to Sotirios Delimanolis.
I am able to resolve the problem by using JSONParser
InputStream in = new BufferedInputStream(conn.getInputStream());
String result = org.apache.commons.io.IOUtils.toString(in, "UTF-8");
JSONParser parser = new JSONParser();
org.json.simple.JSONArray modelArrary =(org.json.simple.JSONArray) parser.parse(result) ;
System.out.println(modelArrary);
I am working on an Automation Framework and I am looking for an alternative for excel to store test data, element locators and page objects.
So one my friend working on Automation is using json file to store all data as its easy and faster in reading and writing data, Also it can be easy in maintaining. They are using ruby as the language.
So I wanted to know if we can do the same using java & selenium to achieve this?
I have searched google for this and it looks like there is a library called "gson" from google, but none that shows how to use it using selenium.
please share your thoughts on this.
Thank you!!
I can't speak to including element locators in a JSON file, as I follow the page object model and include all those in the java classes. However, reading test data from a JSON file is very easy. It's been a while since I've messed around with this, but I used JSON Simple (which I still use to generate JSON objects/files) and did something like this to read in the file:
protected JSONObject getDataFile(String dataFileName) {
String dataFilePath = "src/test/resources/";
JSONObject testObject = null;
try {
FileReader reader = new FileReader(dataFilePath + dataFileName);
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
testObject = (JSONObject) jsonObject;
} catch (Exception ex) {
ex.printStackTrace();
}
return testObject;
}
Once you have the JSON Object, JSON simple provides a few different ways to interact with it and get the values. I've played around with Gson a while back and I think that was fairly similar.
I don't know how your data file is/will be structured, but I had a key string that represented a test case name, and the value was a json object that contained other key-value pairs with the actual data and I fed that data to a TestNG data provider. If that is similar to your setup, I can share that code.
EDIT: Here is the method used by the #DataProvider
public Object[][] getTestScenarios(String dataFileName, String testCaseName) {
JSONArray testCase = (JSONArray) getDataFile(dataFileName).get(testCaseName);
List<JSONObject> testScenarioArray = new ArrayList<JSONObject>();
for (int i = 0; i < testCase.size(); i++) {
testScenarioArray.add((JSONObject) testCase.get(i));
}
Object[][] dataProviderArray = new Object[testScenarioArray.size()][];
for (int scenario = 0; scenario < testScenarioArray.size(); scenario++) {
String scenarioName = null;
if ((String) testScenarioArray.get(scenario).get("scenario") != null) {
scenarioName = (String) testScenarioArray.get(scenario).get("scenario");
} else {
scenarioName = "No scenario name specified";
};
dataProviderArray[scenario] = new Object[] { scenarioName, (JSONObject) testScenarioArray.get(scenario) };
}
return dataProviderArray;
}
The scenario name stuff could be removed, as I believe I only used that for logging or reporting, if I recall correctly. The reason I had it as a JSONArray and coded in this fashion is so a single test case could have an array with multiple scenarios with differing data. Didn't want the tests to have to care how many scenarios there were.
I have read a JSON Array from DB and made a list of a JSON object from JSON Array.
The array looks as follows:
[{
"index": "data",
"type": "message",
"sum":
{
"message": "HELLO",
},
}, {
"index": "data",
"type": "message",
"sum":
{
"message": "HELLO123",
}
}]
It is collected from DB in STRING form but is an array as it has SQUARE BRACKETS: [{Json1}, {Json2}].
String data = "ArrayFromDB";
JSONArray jsonArr = new JSONArray(data);
List<String> listJSON = new ArrayList<String>();
for (int i = 0; i < jsonArr.length(); i++)
{
listSMSJSON.add(jsonArr.getJSONObject(i).getJSONObject("sum").getString("message"));
}
System.out.println(listJSON);
listJSON is printed as [HELLO, HELLO123]