Get dynamically list of object using json.simple - java

Asking after searching and trying many examples .
I'm trying to dynamically get list of values from json in order to insert into array .
The json looks like :
{
"Test_name":"mft",
"parameters":[
{
"Remotehost":"vl-tlv-ctm-qa22",
"Ftptype":"sftp",
"file_name":"blabla.txt"
}
]
}
i'm using the following code :
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("c:/temp/test.txt"));
JSONObject jsonObject = (JSONObject) obj;
String testname = (String) jsonObject.get("Test_name");
System.out.println(testname)
JSONArray msg = (JSONArray) jsonObject.get("parameters");
Iterator<JSONObject> iterator = msg.iterator();
while (iterator.hasNext()) {
JSONObject factObj = (JSONObject) iterator.next();
System.out.println(factObj);
the output is :
mft
{"Remotehost":"vl-tlv-ctm-qa22","file_name":"blabla.txt","Ftptype":"sftp"}
how do i break the pairs in the nested so i can use the as variables and not as single line ?
Thanks ,
Zohar

You can get the pairs as key-value pair from JSONObject as below:
while (iterator.hasNext()) {
JSONObject factObj = (JSONObject) iterator.next();
for (Object key : factObj.keySet()) {
System.out.println(key+":"+factObj.get(key));
}
}

Related

[Java]: Unable to parse a JSON with no array / sub array in it

I am using the json-simple-1.1.jar
and trying to get multiple (atleast 3) values from the json as shown in the code section.
My code works for a JSON with multiple arrays but not working for simple json format.
{
"Addresses": {
"UserName": "Rahul",
"Status": "Active",
"CreateDate": "2017-01-09T11:39:31.244Z",
"SecretAccessKey": "ABCD-EFGH-HIJK",
"AccessKeyId": "1234567"
}
}
Following is the java logic I am trying to use:
public static String[] getValuesFromJson(String filename, Object key, int exp_sizeOfArray, String[] exp_keys) throws FileNotFoundException, IOException, ParseException {
String valuesFromJson[] = new String[exp_keys.length];
/** Create a JSONParser object*/
JSONParser parser = new JSONParser();
/** Read the JSON file using parser*/
JSONObject jsonObject = (JSONObject) parser.parse(new FileReader(
filename));
System.out.println("JsonObject size: "+jsonObject.keySet().size());
for (Object object : jsonObject.keySet()) {
System.out.println(jsonObject.get(object.toString()));
}
/** Get the values in JSONArray using the key*/
JSONArray jsonArray = (JSONArray) jsonObject.get(key);
for (int i = 0; i < jsonArray.size(); i++) {
/** Add the individual set from JSONArray to a JSONObject */
JSONObject subJsonObject = (JSONObject) parser.parse(jsonArray.get(i).toString());
/** Check for expected size of array */
if(subJsonObject.size() <= exp_sizeOfArray){
int index=0;
/** Check for each key value in the sub-JSONObject keySet*/
for (Object object : subJsonObject.keySet()) {
/** Iterate until the expected key value matches with the actual value*/
for (int j = 0; j < exp_keys.length; j++) {
/** Check if the expected key matches with any of the key value*/
if(object.toString().trim().equals(exp_keys[j].toString().trim())){
System.out.println("Key: '".concat(object.toString()).concat("'\tValue: '").concat(subJsonObject.get(object)+"'"));
valuesFromJson[index] = subJsonObject.get(exp_keys[j]).toString();
index++;
break;
}
}
}
}
}
/** Return the value of expected key*/
return valuesFromJson;
}
I am getting error: "org.json.simple.JSONObject cannot be cast to org.json.simple.JSONArray" on below line:
JSONArray jsonArray = (JSONArray) jsonObject.get(key);
You are trying to cast JSONObject to JSONArray, but there is no array. Rather get all object keys and iterate over it.
If you go to json.org(1) you can find there:
An array is an ordered collection of values. An array begins with [ (left bracket) and ends with ] (right bracket). Values are separated by , (comma)
Voila!
Done it without converting JSONObject to JSONArray
JSONObject jsonObject = (JSONObject) parser.parse(new FileReader(
filename));
/** Creating another JSONObject here */
JSONObject jsonObject2 = (JSONObject) parser.parse(jsonObject.get(key).toString());
for (Object newKey : jsonObject2.keySet()) {
System.out.println("Key: '".concat(newKey.toString()).concat("'\tValue: '").concat(jsonObject2.get(newKey)+"'"));
}
Thank you guys for the help!

JSONSimple key finder for array

There is a very nice KeyFinder example on the json-simple docs
But if I try to get an array, it will only return me the first element
json
{"foo":
{"bar":
{"foobar":{
"items":["item1","item2","item3"]
}
}
}
}
If I use the example of keyFinder and search for "items", I only get "item1" whereas I want to be able to use the whole array.
Example of what the keyFinder does / how it is working:
KeyFinder finder = new KeyFinder();
finder.setMatchKey("items");
try{
while(!finder.isEnd()){
if(finder.isFound)
System.out.println("finder.getValue() -->" + finder.getValue()
}
}//...
How I do currently:
Object obj = parser.parse(jsonText);
JSONObject jsonObject = (JSONObject) obj;
JSONObject jsonTags = (JSONObject) ((JSONObject) ((JSONObject) jsonObject.get("foo")).get("bar")).get("foobar");
String tags = (String) jsonTags.get("items").toString().replaceAll("[^A-Za-z0-9,]","");
String[] vaca = tags.split(",");
for(String s : vaca) {
list.add(s);
System.out.println(s);
}
My question is how to get the array without knowing the "path" foo >> bar >> foobar to get the "items" array by its key.
It will give you full array. One mistake you were making is you didn't wrapped foo, bar and foobar in "". It should be like this :
{"foo":
{"bar":
{"foobar":{
"items":["item1","item2","item3"]
}
}
}
}
I tried your code
JSONParser parser = new JSONParser();
Object obj = parser.parse(jsonText);
JSONObject jsonObject = (JSONObject) obj;
JSONObject jsonTags = (JSONObject) ((JSONObject) ((JSONObject) jsonObject.get("foo")).get("bar")).get("foobar");
String tags = (String) jsonTags.get("items").toString().replaceAll("[^A-Za-z0-9,]","");
String[] vaca = tags.split(",");
List<String> list = new ArrayList<>();
for(String s : vaca) {
list.add(s);
System.out.println(s);
}
And the output is :
item1
item2
item3

Create JSON in 2D array to store key value pair

I have a question that would like to seek your expertise on.
I have Class call Technology and i retrieve data from the DB as object list of Technology classtechnologyList= getProjectBD().getAllTechnology();
my question is how to store data as key value pair in Json array.
This is my code
JSONArray technologyArray=new JSONArray();
for (Technology technology : technologyList) {
JSONArray gridRow=new JSONArray();
gridRow.put(technology.getTechnologyId());
gridRow.put(technology.getTechnologyName());
technologyArray.put(gridRow);
}
I need to pass this data to select option in my jsp as id and name.
ex:-[1:JAVA,2:C#...]
Try to use com.google.gson.* elements like that :
private JsonArray serializetechnologies(List<Technology> technologyList) {
JsonArray jsonArray = new JsonArray();
for (Technology technology : technologyList) {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty(technology.getTechnologyId()+"", technology.getTechnologyName());
jsonArray.add(jsonObject);
}
return jsonArray;
}
And if you want to get value :
for (JsonElement jsonElement : jsonArray) {
JsonObject jsonObject = (JsonObject) jsonElement;
String name = jsonObject.get(technologyX.getTechnologyId() + "").getAsString();
System.out.println("The name of technology witch Id = " + technologyX.getTechnologyId() + " is : "
+ name);
}
I hope that will help :)

Error parsing the JSON file using Java

I am getting the error while parsing the the following JSON file. If anybody please help me out, highly appreciated!
{"Name":"Abc", "Author":"fgd", "Company List":{"Company":"C1","Companyone":"Compa2"}}
Here is my code:-
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("/Users/abcdefgh/Documents/File1.txt"));
JSONObject jsonObject = (JSONObject) obj;
String name = (String) jsonObject.get("Name");
String author = (String) jsonObject.get("Author");
System.out.println("Name: " + name);
System.out.println("Author: " + author);
// JSONArray companyList= new JSONArray();
//companyList.add(obj);
JSONArray companyList = (JSONArray) jsonObject.get("Company List");
System.out.println("Company List:");
/* for (int i=0;i<2;i++){
System.out.println(companyList.get(i));
}
*/Iterator<String> iterator = companyList.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
Output:-
Name: Abc
Author: fgd
java.lang.ClassCastException: org.json.simple.JSONObject cannot be
cast to org.json.simple.JSONArray at
com.selenium.test.JSONRead.main(JSONRead.java:29)
The property type of "Company List" property is object, not an array.
Replace the line
JSONArray companyList = (JSONArray) jsonObject.get("Company List");
for:
JSONObject companyList = jsonObject.getJSONObject("Company List");
If you want to get the values ​​of this object, you can do the following:
JSONObject companyList = jsonObject.getJSONObject("Company List");
String company = companyList.getString("Company");
And remember to get the value of a property of a JSONObject which is an array, you must use the method getJSONArray.
companyList is a JSON Object, not an array. That's why you are getting that class cast exception.

How to retrieve JSON data inside an JSON object?

I have a JSON Object that looks like this :
"TripList":{
"noNamespaceSchemaLocation":"http://api.vasttrafik.se/v1/hafasRestTrip.xsd",
"servertime":"11:27",
"serverdate":"2013-04-02",
"Trip":[{
"Leg":{
"name":"Spårvagn 3",
"type":"TRAM",
"id":"9015014500300079",
"direction":"Kålltorp",
"fgColor":"#004b85",
"bgColor":"#ffffff",
"stroke":"Solid",
"accessibility":"wheelChair",
"Origin":{
"name":"Brunnsparken, Göteborg",
"type":"ST",
"id":"9022014001760004",
"routeIdx":"19",
"time":"11:27",
"date":"2013-04-02",
"track":"D ",
"rtTime":"11:31",
"rtDate":"2013-04-02",
"$":"\n"
}
to get the name inside the Leg object is working fine.
But if I wanna get thetime inside the Origin object how do I do that?
My code is like this so far:
JSONParser parser = new JSONParser();
Object obj = parser.parse(Planner.getPlanner().getJsonDataForTrip(Planner.getPlanner().getStartLocationID(), Planner.getPlanner().getDestinationID()));
JSONObject topObject = (JSONObject) obj;
JSONObject locationList = (JSONObject) topObject.get("TripList");
JSONArray array = (JSONArray) locationList.get("Trip");
Iterator<JSONObject> iterator = array.iterator();
while (iterator.hasNext()) {
JSONObject jsonObj = iterator.next();
jsonObj = (JSONObject) jsonObj.get("Leg");
String line = (String) jsonObj.get("name");
Planner.getPlanner().setLines(line);
System.out.println(jsonObj.get("Origin"));
Long time = (Long) jsonObj.get("time");
String track =(String) jsonObj.get("track");
System.out.println(line);
System.out.println(time);
System.out.println(track);
}
}
And in the console it say like this :
{"routeIdx":"19","id":"9022014001760004","rtDate":"20130402","time":"15:02","$":"\n","name:"Brunnsparken, Göteborg","track":"D ","rtTime":"15:06","date":"2013-04-02","type":"ST"}
Spårvagn 3
null
null
So basiclly i am getting the name Spårvang 3 already. But I wanna get the time.
so the time that I am trying to get out by using jsonObj.get("time"); is giving a null value.
Whats the problem and how can I get the time from the object "Origin"??
Since "Time" is part of the "Origin"-object, you would need to extract the "Origin"-object first:
JSONOject origin = (JSONObject) jsonObj.get("Origin");
And then:
String time = origin.getString("time");
You are getting 'time' and 'track' properties of 'Leg' object, not the 'Origin' object..
It should be:
JSONParser parser = new JSONParser();
Object obj = parser.parse(Planner.getPlanner().getJsonDataForTrip(Planner.getPlanner().getStartLocationID(), Planner.getPlanner().getDestinationID()));
JSONObject topObject = (JSONObject) obj;
JSONObject locationList = (JSONObject) topObject.get("TripList");
JSONArray array = (JSONArray) locationList.get("Trip");
Iterator<JSONObject> iterator = array.iterator();
while (iterator.hasNext()) {
JSONObject jsonObj = iterator.next();
jsonObj = (JSONObject) jsonObj.get("Leg");
String line = (String) jsonObj.get("name");
Planner.getPlanner().setLines(line);
System.out.println(jsonObj.get("Origin"));
// Added this line
jsonObj = (JSONObject) jsonObj.get("Origin");
String time = (String) jsonObj.get("time");
String track =(String) jsonObj.get("track");
System.out.println(line);
System.out.println(time);
System.out.println(track);
}
Do following code
JSONOject origin = (JSONObject) jsonObj.get("Origin");
String time = (String) origin.getString("time");
them use SimpleDateFormat to parse time string and get date object

Categories

Resources