JSONSimple key finder for array - java

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

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!

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

Java extract from nested JSON

I want to use financial data from yahoo in my program, it already works. I get the complete JSON content and I can display it. But now I want to extract the price as int.
public class Main {
public static void main (String[]args) throws IOException {
String sURL = "http://finance.yahoo.com/webservice/v1/symbols/googl/quote?format=json"; //just a string
// Connect to the URL using java's native library
URL url = new URL(sURL);
HttpURLConnection request = (HttpURLConnection) url.openConnection();
request.connect();
// Convert to a JSON object to print data
JsonParser jp = new JsonParser(); //from gson
JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); //convert the input stream to a json element
JsonObject rootobj = root.getAsJsonObject(); //may be an array, may be an object.
System.out.print(rootobj);
}
}
EDIT
This is the JSON data from yahoo
{
"list" : {
"meta" : {
"type" : "resource-list",
"start" : 0,
"count" : 1
},
"resources" : [
{
"resource" : {
"classname" : "Quote",
"fields" : {
"name" : "Google Inc.",
"price" : "554.520020",
"symbol" : "GOOGL",
"ts" : "1432324800",
"type" : "equity",
"utctime" : "2015-05-22T20:00:00+0000",
"volume" : "1213288"
}
}
}
]
}
}
EDIT 2
I changed my code
JsonParser jp = new JsonParser(); //from gson
JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); //convert the input stream to a json element
JsonObject obj = root.getAsJsonObject();
JsonObject result = obj.get("list").getAsJsonObject();
String result2 = result.get("resources").toString();
System.out.print(result2);
And now I already get this
[{"resource":{"classname":"Quote","fields":{"name":"Google Inc.","price":"554.520020","symbol":"GOOGL","ts":"1432324800","type":"equity","utctime":"2015-05-22T20:00:00+0000","volume":"1213288"}}}]
How can I get the "price" now?
EDIT 3
Ok I got it now, it works and I only get the price as double, but is this a smart way to solve this task?
// Convert to a JSON object to print data
JsonParser jp = new JsonParser(); //from gson
JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); //convert the input stream to a json element
JsonObject obj = root.getAsJsonObject();
JsonObject result = obj.get("list").getAsJsonObject();
JsonArray result2 = result.get("resources").getAsJsonArray();
JsonObject result3 = result2.get(0).getAsJsonObject();
JsonObject result4 = result3.get("resource").getAsJsonObject();
JsonObject result5 = result4.get("fields").getAsJsonObject();
String result6 = result5.get("price").toString();
result6 = result6.replace("\"", "");
double value = Double.parseDouble(result6);
System.out.print(value);
you should reach "fields" object to extract "name", "price" etc.
The org.json library is easy to use. Example code below: your response as a string :
JSONObject obj1 = new JSONObject(response);
JSONArray arr = obj1.getJSONObject("list").getJSONArray("resources"); //GETS RESOURCES ARRAY
for (int i = 0; i < arr.length(); i++)
{
String resource = arr.getJSONObject(i).toString();
JSONObject obj2 = new JSONObject(resource);
String resourceObject = obj2.getJSONObject("resource").toString(); //RESOURCE OBJECT
JSONObject obj3 = new JSONObject(resourceObject);
String name = obj3.getJSONObject("fields").getString("name"); //REACHED THE FIELDS
float price = (float)obj3.getJSONObject("fields").getDouble("price");
System.out.println(name);
System.out.println(price);
}
Download : http://mvnrepository.com/artifact/org.json/json
He is already using gson.
If you want to continue using gson and know the structure before, you could create classes that stores the data.
class GoogleRequest{
private GoogleList list;
public GoogleList getList() {
return list;
}
public void setList(GoogleList list) {
this.list = list;
}
}
// class for list
class GoogleList{
private Meta meta;
private List<Resources> resources;
public List<Resources> getResources() {
return resources;
}
public void setResources(List<Resources> resources) {
this.resources = resources;
}
public Meta getMeta() {
return meta;
}
public void setMeta(Meta meta) {
this.meta = meta;
}
}
// create other classes here like the Resources class
JsonParser jp = new JsonParser(); // from gson
JsonElement root = jp.parse(new InputStreamReader((InputStream)request.getContent()));
GoogleRequest list = new Gson().fromJson(root,GoogleRequest.class);
The GoogleRequest should hold a List object and a Meta object. gson will introspect and set the properties. gson will set properties to null if they where not introspected. So you could use.
if( list.getResources() != null ){
// list is here
}else{
// do some other code and parse diffrent json
}
If you don't know if it is a array or object create different classes to handle it for you. Just parse the data with new Gson().fromJson();
Now remember that you need right properties for the job. Let's say you have this json in java
String json = "{\"price\" : \"554.520020\"}";
Then price needs to be Double or double. If you use Double you could check
if( obj.getPrice() != null ){
System.out.println( obj.getPrice().intValue() );
}
Note: you will loose precision if you cast double to int

Parse JSON string in Java without keys

I am new to parsing JSON in java. I have this JSON string:
[
{
"projectId":5,
"userName":"clinician",
"projectName":"r",
"projectSummary":"r",
"projectLanguage":"r",
"contactPersonName":"r",
"contactPersonCV":"r",
"contactPersonEmail":"r",
"contactPersonPhone":"r"
},
[
{
"consentFileId":2,
"projectId":5,
"consentDescription":"r",
"consentFileName":"test.pdf",
"servicePathToGetConsentPdf":null
},
{
"consentFileId":3,
"projectId":5,
"consentDescription":"rrr",
"consentFileName":"test.pdf",
"servicePathToGetConsentPdf":"localhost:8080/4c_viewFile?consentFileId=3"
}
],
[
{
"anonymized_patient_identifier":"r",
"projectId":5
},
{
"anonymized_patient_identifier":"2",
"projectId":5
},
{
"anonymized_patient_identifier":"5",
"projectId":5
}
]
]
I have managed to get values from simpler JSON strings but this one has multiple levels and also there is no key in each level. I tried with simple code like this:
Object obj = parser.parse(data);
JSONObject jsonObject = (JSONObject) obj;
resultJson = (String) jsonObject.get("projectId");
resultJson += "\n";
resultJson += (String) jsonObject.get("userName");
but I get the error [java.lang.ClassCastException: org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject] And also I don't understand how I will get the values in lower level without a key. I tried also to save it as a JSONArray but it didn't work.
your root of json is type of JSONArray,
the first object stored in the root array is an object, you can retrieve it by using index = 0 .
this is a hack to make your code work:
JSONArray jsonArray = JSONArray.fromObject(data);
JSONObject jsonObject=obj.getJSONObject(0);
resultJson = (String) jsonObject.get("projectId");
resultJson += "\n";
resultJson += (String) jsonObject.get("userName");
NOTE:
to convert a String to JSONArray, you can do :
JSONArray array = JSONArray.fromObject(data);
To improve on nafas answer, I would do this to see all the objects in the array:
Object obj = parser.parse(data);
JSONArray jsonArray = (JSONArray) obj;
for (int i = 0; i < jsonArray.size (); i++) {
JSONObject jsonObject=obj.getJSONObject(i);
resultJson = (String) jsonObject.get("projectId");
resultJson += "\n";
resultJson += (String) jsonObject.get("userName");
}

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