How to retrieve JSON data inside an JSON object? - java

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

Related

Get dynamically list of object using json.simple

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));
}
}

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

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.

Getting Json object inside a Json object in Java

So I have some code that is able to send this out:
{"id":1,
"method":"addWaypoint",
"jsonrpc":"2.0",
"params":[
{
"lon":2,
"name":"name",
"lat":1,
"ele":3
}
]
}
The server receives this JSON object as a string named "clientstring":
JSONObject obj = new JSONObject(clientstring); //Make string a JSONObject
String method = obj.getString("method"); //Pulls out the corresponding method
Now, I want to be able to get the "params" value of {"lon":2,"name":"name","lat":1,"ele":3} just like how I got the "method".
however both of these have given me exceptions:
String params = obj.getString("params");
and
JSONObject params = obj.getJSONObject("params");
I'm really at a loss how I can store and use {"lon":2,"name":"name","lat":1,"ele":3} without getting an exception, it's legal JSON yet it can't be stored as an JSONObject? I dont understand.
Any help is VERY appreciated, thanks!
params in your case is not a JSONObject, but it is a JSONArray.
So all you need to do is first fetch the JSONArray and then fetch the first element of that array as the JSONObject.
JSONObject obj = new JSONObject(clientstring);
JSONArray params = obj.getJsonArray("params");
JSONObject param1 = params.getJsonObject(0);
How try like that
JSONObject obj = new JSONObject(clientstring);
JSONArray paramsArr = obj.getJSONArray("params");
JSONObject param1 = paramsArr.getJSONObject(0);
//now get required values by key
System.out.println(param1.getInt("lon"));
System.out.println(param1.getString("name"));
System.out.println(param1.getInt("lat"));
System.out.println(param1.getInt("ele"));
Here "params" is not an object but an array. So you have to parse using:
JSONArray jsondata = obj.getJSONArray("params");
for (int j = 0; j < jsondata.length(); j++) {
JSONObject obj1 = jsondata.getJSONObject(j);
String longitude = obj1.getString("lon");
String name = obj1.getString("name");
String latitude = obj1.getString("lat");
String element = obj1.getString("ele");
}

Android: How to get certain values from JSON

I have the following code in my main activity.
JSONObject jObj = new JSONObject(loadJSONFromAsset());
jObj.getJSONObject("body");
The contents of jObj looks like this:
{
"body" : {
"name" : {
"test" : "abc"
}
}
}
I can get the value of "body" by iterating "jObj.keys()", but how can I get the value of "name"?
Use this:
JSONObject jObj = new JSONObject(loadJSONFromAsset());
JSONObject objectName = jObj.getJSONObject("body").getJSONObject("name");
String test = objectName.getString("test"); //return abc
Try this..
JSONObject jObj = new JSONObject(loadJSONFromAsset());
JSONObject js = jObj.getJSONObject("body");
JSONObject jo = js.getJSONObject("name");
System.out.println("test value "+jo.getString("test");

Categories

Resources