I will keep it simple - trying to print the username ('user') value of this JSON file with JACKSON:
{
"creds" : {
"user": "Y9CJG1756",
"pass": "12222#$1"
},
"env": {
"qa": {
"url": "https://www.walla.com/"
}
}
}
I'm running this function but could only find a way to print the entire string of the object 'creds' instead of just the user name.
public static void isJsonStringWorks(String filePath) {
try {
JsonNode objectValue;
byte[] jsonData = Files.readAllBytes(Paths.get(filePath));
ObjectMapper objectMapper = new ObjectMapper();
JsonNode rootNode = objectMapper.readTree(jsonData);
objectValue = rootNode.get("creds");
System.out.println("object is: " + objectValue + " ,\n" + rootNode);
} catch (Exception e) {
System.out.println("Could not read the JSON file");
}
}
Really appreciate the help.
The correct code would be:
objectValue = rootNode.get("creds").get("user").asText()
Also you shall consider the following options:
Introduce Java representation of your data model and read source JSON string as Java object (using objectMapper.readValue(...) method). After that it will be possible to access values like usual Java beans (root.getCreds().getUser())
Using JsonPath to access "deep" values inside JSON to simplify JSON values lookup. For example creds/user value could be obtained like:
String json = "...";
Object document = Configuration.defaultConfiguration().jsonProvider().parse(json);
String value = JsonPath.read(document, "$.creds.user")
you are on right route.
You can call objectValue.get('user')
Related
I am trying to return data from a nested JSON Object in a seperate JSON file. For example, my JSON file might look like this
{
"user1": {
"name": "John",
"age": 25,
"job": "developer"
},
"day": "May 2nd 2022"
}
And here is the method that I am using to pull the nested Object
public static Object get(String key, String... objKey) throws Exception {
//create new JSON parser and FileReader
JSONParser parser = new JSONParser();
FileReader jsonFile = new FileReader(path);
//Reads the data in JSON file and assigns to Object jsonData
Object jsonData = parser.parse(jsonFile);
//assigns data to a JSONObject object
JSONObject jsonDataObj = (JSONObject) jsonData;
//checks to see if data is an array
if(jsonDataObj.get(key).getClass().isArray()){
throw new Error("Data is an array and not returnable");
}
if(jsonDataObj.get(key) instanceof JSONArray){
//get JSON Object into JSONObject variable to read from
JSONObject jsonObj = (JSONObject) jsonDataObj.get(key);
//get wanted data from nested JSON Object
Object wantedData = jsonObj.get(objKey);
return wantedData;
} else {
//get data associated with 'key' value in JSON Object
Object wantedData = jsonDataObj.get(key);
return wantedData;
}
} //end get()
When I call the method get() with only one param like get("day") it returns the data in day perfectly fine and nothing goes wrong. The problem is when I call the method and introduce a second argument it returns null.
For example, if I call get("user1", "age") instead of returning 25 is return null. I figured out that it is the vararg parameter that is messing it up since when I change the method parameters to String key, String objKey it works fine. Another thing that i've noticed while debuging is that if I print the vararg it prints a memory address instead of the String passed to the parameter.
If it is of any help; I am using the json-simple library on Maven 1.4
I am working in JAVA 1.8 to write and using Apache Tomcat to run the server, I am unable to retrieve data from a POST request i.e in JSON.
I actually need it in an HashMap and I can even parse and convert it into HashMap even if it is readable in JSON. I have tried several links on the internet and I always get exception like Could not deserialize to type interface PACKAGE NAME.
#POST
#Produces("application/json")
#Consumes("application/json")
#Path("ClassifyCase")
public Rules Classify(HttpServletRequest request) {
StringBuffer jb = new StringBuffer();
String line = null;
try {
BufferedReader reader = request.getReader();
while ((line = reader.readLine()) != null)
jb.append(line);
} catch (Exception e) { System.out.println("Buffer Reader Error"); }
System.out.println("What I read: "+jb);
System.out.println("Here la la l ala ");
// System.out.println("Case: ++ "+Case.toString());
System.out.println("Here la la l ala ");
Rules foundRule = new Rules();
// List<Rules> objListRules = new ArrayList<Rules>();
try
{
DataAccessInterface objDAInterface = new RuleDataAdapter();
AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
// foundRule = objADBridge.Classify(Case);
logger.info("Classification done!");
}
catch(Exception ex)
{
logger.info("Error in classification");
System.out.println("Couldnt Classify Properly!");
// return
}
return foundRule;
}
Can someone please share a guide on how can I receive this data and convert it into a Map or either I can directly get a Map!
I strongly recommend you to use this library of JSON..
You can find it in Maven Repository and it's so easy to parse a JSON to a Map or to a JSONArray or JSONObject... depends of your necessity what you want to do..
Here is a example show how to parse a JSON to a HashMap
Map<String, Object> map = new JSONObject(--JSONString here--).toMap();
And that's all...
Now, if your JSON has a list of objects, i mean like a list of maps, what you just need to do is this...
JSONArray jsonArray = new JSONArray(--JSON string here--);
for(int i = 0; i < jsonArray.length(); i++){
Map<String, Object> map = jsonArray.getJSONObject(i).toMap();
}
Here is the explanation.
You take you JSON string and pass it as a parameter to the JSONArray,what JSONArray does is, take your json string a parse it to like a list
Then you make a for to get each Object of that list and parse it to a map.
Note: what the JSONObject does, is take the object of the JSONArray and parse it... you can parse it to a map or you can get each object of that map..
String jsonString = "{\n" +
"\t\"1\": \"1\",\n" +
"\t\"FPG\": \"50\",\n" +
"\t\"Symptoms\": \"Yes\"\n" +
"}";
Map<String, String> map = new Gson().fromJson(jsonString, Map.class);
for (String key: map.keySet()) {
System.out.println(map.get(key));
}
The request you send does not contain proper JSON in the body. You are missing the commas ",". It should be something like this:
{
"1":"1",
"FPG":"50",
"Symptoms":"yes"
}
Just change it and give proper JSON format to the message.
Even if the request was not in your control, I would strongly suggest that you contacted the service that creates the message and asked from them to fix it.
It would be the last resort for me to make my own deserializer to handle an "inproper" message.
An easy way to check if your JSON is properly formated is an online formatter, e.g. https://jsonformatter.org/
My JSON Structure will vary depend on the request. But the content inside each element remain same. For Example:
JSON1:
{
"h1": {
"s1":"s2"
},
"c1": {
"t1:""t2"
}
}
JSON2:
{
"h1": {
"s1":"s2"
},
"c2": {
"x1:""x2"
}
}
In the above example, elements inside h1,c1 and c2 are constant. Please let me know how to convert JSON to JAVA Object
Regards
Udhaya
First of all You need to understand Json Structure cause above format is incorrect visit this
and this
And you can use Google Gson or Json for parsing the result json String .
"t1:""t2" json format incorrect
Used
"t1":"t2"
Instead of
"t1:""t2"
and also used
"x1": "x2"
Instead of
"x1:""X2"
Code to take in java
try {
JSONObject jsonObject = new JSONObject(response);
JSONObject jsonsubObject = jsonObject.getJSONObject("h1");
String s1 = jsonsubObject.getString("s2");
JSONObject jsonsubObject1 = jsonObject.getJSONObject("c1");
String t1 = jsonsubObject1 .getString("t2");
}
catch (JSONException e) {
e.printStackTrace();
}
Use Google Gson:
Gson gson = new Gson();
ClassName object;
try {
object = gson.fromJson(json, ClassName.class);
} catch (com.google.gson.JsonSyntaxException ex) {
//the json wasn't valid json
}
String validJson = gson.toJson(obj); //obj is an instance of any class
json must be a valid JSON String
import org.json.JSONObject;
you can simple pass your data in constructor of JSONObject it automatically handle, you need to throws JSONException which may occur during conversion id format of data is not correct
String data = "{'h1':{'s1':'s2'},'c1':{'t1:''t2'}}";
JSONObject jsnobject = new JSONObject(data);
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]
hi I'm trying to get all 'id' value from my json into my 'results' array.
I didn't really understood how the json class of libgdx works, but I know how json works itself.
Here is the json : http://pastebin.com/qu71EnMx
Here is my code :
Array<Integer> results = new Array<Integer>();
Json jsonObject = new Json(OutputType.json);
JsonReader jsonReader = new JsonReader();
JsonValue jv = null;
JsonValue jv_array = null;
//
try {
String str = jsonObject.toJson(jsonString);
jv = jsonReader.parse(str);
} catch (SerializationException e) {
//show error
}
//
try {
jv_array = jv.get("table");
} catch (SerializationException e) {
//show error
}
//
for (int i = 0; i < jv_array.size; i++) {
//
try {
jv_array.get(i).get("name").asString();
results.add(new sic_PlayerInfos(
jv_array.get(i).get("id").asInt()
));
} catch (SerializationException e) {
//show error
}
}
Here is the error I get : 'Nullpointer' on jv_array.size
Doing it this way will result in a very hacky, not maintainable code. Your JSON file looks very simple but your code is terrible if you parse the whole JSON file yourself. Just imagine how it will look like if you are having more than an id, which is probably going to happen.
The much more clean way is object oriented. Create an object structure, which resembles the structure of your JSON file. In your case this might look like the following:
public class Data {
public Array<TableEntry> table;
}
public class TableEntry {
public int id;
}
Now you can easily deserialize the JSON with libgdx without any custom serializers, because libgdx uses reflection to handle most standard cases.
Json json = new Json();
json.setTypeName(null);
json.setUsePrototypes(false);
json.setIgnoreUnknownFields(true);
json.setOutputType(OutputType.json);
// I'm using your file as a String here, but you can supply the file as well
Data data = json.fromJson(Data.class, "{\"table\": [{\"id\": 1},{\"id\": 2},{\"id\": 3},{\"id\": 4}]}");
Now you've got a plain old java object (POJO) which contains all the information you need and you can process it however you want.
Array<Integer> results = new Array<Integer>();
for (TableEntry entry : data.table) {
results.add(entry.id);
}
Done. Very clean code and easily extendable.