I have this code block that iterates over the all keys in my JSONObject, jsonObject1 is a json object that has 1 key and bunch of json data as the value of this single key. So it look like this {"singleKey":"{"anotherKey":"anotherValue"}, {"someKey":"someValue"}"}
JSONObject jsonObject1 = new JSONObject(mystring);
Iterator<String> iter = jsonObject1.keys();
while(iter.hasNext())
{
String key = iter.next();
JSONObject jsonObject2 = new JSONObject(jsonObject1.getString(key));
key1 = jsonObject2.getString("key");
value1 = jsonObject2.getString("value");
String place += "\n" + key1 + ": " + value1;
}
What I want is, I want this while loop starts from the last key of the jsonObject2 and iterates over to the first key. So I will start adding to my place string starting from the last value of the jsonObject2. The first value of place string will be someKey: someValue (the last element of the JSONObject).
How can I start this iteration starting from the last key of the json object?
OK, try this (haven't fully tested):
public void jsonMethod(String mystring) throws JSONException {
JSONObject jsonObject1 = new JSONObject(mystring);
Iterator<String> iter = jsonObject1.keys();
ArrayList<String> keySet = new ArrayList<>();
while(iter.hasNext()){
keySet.add(iter.next());
}
Collections.reverse(keySet);
for(String myKey: keySet){
JSONObject jsonObject2 = new JSONObject(jsonObject1.getString(myKey));
// Do your existing stuff with jsonObject2
}
}
Am comparing javascript array of elements with other elements within the same array. If elements are same means, I have to give the same number for all the common elements. If the elements are different I have to give some different number for all the nonidentical elements in another element.
for example :
Array structure = [{Location, Date, Number}]
array = [{ 'LA','2017-12-01',1},
{ 'LA','2017-12-01',1},
{ 'NY','2017-12-01',2},
{ 'NY','2016-10-01',3},
{ 'LA','2017-12-01',1},
{ 'LA','2017-12-01',1},
{ 'LA','2017-12-01',1}]
In this array 'Number' is dynamic element, It should be populate on the following rules.
`key1 = location + '-' +date;`
Consider Key1 is the first element ( combination of location + date ). If the same key1 is present in the array, then 'Number' is common for all the same Key1.
In the above example {'LA','2017-12-01',1 } having the same number 1.
{ 'NY','2017-12-01',2} having the number 2. and { 'NY','2016-10-01',3}, having the number 3 because eventhough location is common but date is different.
Please find my code below that am trying. But it giving same number for all the array elements.
JSONObject orderObj=database.getOrder(salesorderId);
JSONArray lineArr = orderObj.getJSONArray("order_items"); //lines
JSONObject lineObj = null;
for(int i=0;i<lineArr.length();i++)
{
lineObj = lineArr.getJSONObject(i);
String source_location=lineObj.getString("source_location");
String key=source_location.concat(lineObj.has("ship_date") ?
lineObj.getString("ship_date") : lineObj.getString("req_ship_date"));
Map map=new HashMap();
if(!map.containsKey(key)){
map.put(key, map.size()+1);
}
lineObj.put("number", map.get(key).toString());
}
orderObj.append("order_items", lineObj);
Move the instantiating of map out of the for loop:
JSONObject orderObj = database.getOrder(salesorderId);
JSONArray lineArr = orderObj.getJSONArray("order_items"); //lines
JSONObject lineObj = null;
// To here:
Map map = new HashMap();
for ( int i = 0; i < lineArr.length(); ++i )
{
lineObj = lineArr.getJSONObject(i);
String source_location = lineObj.getString("source_location");
String key = source_location.concat( lineObj.has("ship_date") ?
lineObj.getString("ship_date") : lineObj.getString("req_ship_date"));
// From here: Map map=new HashMap();
if ( !map.containsKey(key) )
{
map.put(key, map.size() + 1);
}
lineObj.put("number", map.get(key).toString());
}
orderObj.append("order_items", lineObj);
I have following JSONObject (not array, which I don't mind to convert). I am trying to do two things:
get the count of genre entry as "poetry" (count = 2).
get the key value of author name and genre:
authorName = malcolm
genreName = newsarticle
authorName = keats
genreName = poetry
{ "AddressBook" :{
"Details" :{
"authorname" :{
"Author-malcolm":{
"genre" :"poetry"
}
"Author-keats":{
"genre" :"poetry"
}
}
}
}
}
Code which I tried:
public static void main(String[] args) throws Exception, IOException, ParseException {
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("My path to JSON"));
JSONObject jsonObject = (JSONObject) obj;
JSONArray arrayhere = new JSONArray();
arrayhere.add(obj);
System.out.println(arrayhere);
int count = 0;
for(int i = 0; i < arrayhere.size(); i++) {
JSONObject element = arrayhere.getJSONObject(i);//The method getJSONObject(int) is undefined for the type JSONArray
String branchName = element.getString("genre");//The method getString(String) is undefined for the type JSONObject
if(branchName.equals("poetry")) {
count ++;
}
}
System.out.println("Count f0r poetry genre=" + count);
}
}
I have looked at solutions all over. There is no question similar to this at stackoverflow. I am not sure if the procedure is correct.
A few problems here.
First, I'm not sure where you got that example JSON but you can't work with that. That's not even valid JSON Formatting.
Looks like you want something like this:
{
AddressBook:
[
{
authorname: "author-malcom",
genre:"poetry"
},
{
authorname: "author-keats",
genre: "poetry"
}
]
}
That's the structure you're trying to create in JSON.
So, you're parsing this in from a file into a JSONObject that has a key called AddressBook inside of it. That key points to an array of JSONObjects representing authors. Each of those objects will have a key called genre. You're trying to access the genre key and count on a condition.
What you did above was create attempt to create a JSONObject from an invalid string, and then add the entire JSONObject itself into the JSONArray. JSONArray.add() doesn't convert an object to an array, it literally adds it onto the array.
jsonObj => {"Name":"name1","Id":1000}
jsonArray.add(jsonObj)
jsonArray => [{"Name":"name1","Id":1000}]
That's what you did in your code above. You didn't create an array from a JSONObject, you added an object to the array.
Proper use is going to look like:
Object obj = parser.parse(new FileReader("path_to_file"));
JSONObject jobj = (JSONObject) obj;
//access key AddressBook
JSONArray author_array = jobj.getJSONArray("AddressBook");
int poetry = 0;
for(int i = 0; i < author_array.length(); i++) {
JSONObject author = (JSONObject) author_array.get(i);
if(author.getString("genre").equals("poetry")) {
poetry++;
}
}
To summarize, you're problems come from a lack of understanding about JSON Formatting and how to access elements within a JSON Object.
Paste in the sample JSONObject I gave you above here. That site will let you visualize what you're working with.
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!
I am receiving a json string in the following format:
{"27":{"id":"27","uid":"4","title":"teamer.zapto.org","url":"www.google.jo","ip":"74.125.234.63","enabled":"1","services":{"Http 1":{"status":"1","ts":"1355058071"}},"fetch_interval":"60","ping_shift":"0"},
"30":{"id":"30","uid":"4","title":"google","url":"www.google.com","ip":"74.125.234.114","enabled":"1","services":{"Http 1":{"status":"1","ts":"1355058079"}},"fetch_interval":"60","ping_shift":"0"},
"31":{"id":"31","uid":"4","title":"facebook.com","url":"facebook.com","ip":"69.171.247.21","enabled":"1","services":{"Http 1":{"status":"1","ts":"1355058095"}},"fetch_interval":"60","ping_shift":"0"},
"32":{"id":"32","uid":"4","title":"ebir","url":"www.ebir.com","ip":"74.52.50.226","enabled":"1","services":{"Ftp":{"status":"1","ts":"1355058073"},"Http 1":{"status":"1","ts":"1355058073"}},"fetch_interval":"60","ping_shift":"0"},
"33":{"id":"33","uid":"4","title":"zapto","url":"teamer.zapto.org","ip":"200.35.150.6","enabled":"1","services":{"Http 1":{"status":"0","ts":"1355056146"}},"fetch_interval":"3600","ping_shift":"2"},
"35":{"id":"35","uid":"4","title":"vogella.com","url":"vogella.com","ip":"46.163.79.226","enabled":"1","services":{"Ftp":{"status":"1","ts":"1355058098"},"Http 1":{"status":"1","ts":"1355058098"}},"fetch_interval":"60","ping_shift":"0"},
"36":{"id":"36","uid":"4","title":"msn","url":"www.msn.com","ip":"131.253.13.140","enabled":"1","services":{"Http 1":{"status":"1","ts":"1355058103"}},"fetch_interval":"60","ping_shift":"0"},
"37":{"id":"37","uid":"4","title":"dubizzle.com","url":"www.dubizzle.com","ip":"94.236.93.152","enabled":"1","services":{"Http 1":{"status":"1","ts":"1355058068"}},"fetch_interval":"60","ping_shift":"0"},
"38":{"id":"38","uid":"4","title":"olx.jo","url":"olx.jo","ip":"204.74.99.100","enabled":"1","services":{"Http 1":{"status":"1","ts":"1355058108"}},"fetch_interval":"60","ping_shift":"0"},
"40":{"id":"40","uid":"4","title":"www.sukar.com","url":"www.sukar.com","ip":"72.52.8.195","enabled":"1","services":{"Ftp":{"status":"0","ts":"1355058092"},"Http 1":{"status":"1","ts":"1355058092"}},"fetch_interval":"60","ping_shift":"0"}}
as you can see the keys are numbers (27, 30, 31,...) and are not consecutive. How can I get the data from such json? I know that it must be some kind of loop depending on length but I couldn't figure it out on how to do so. Usually I'd use jObject.getString("id"), but since I don't know what the string would be what can I do?
If you have a JSONObject as the root, you should be able to do the following:
JSONObject root = new JSONObject(jsonString);
JSONArray names = root.names();
for(int i = 0; i < names.length(); i++) {
String tag = names.getString(i);
...
}
The tag will be the numeric tag you refer to.
JSONObject questionMark = new JSONObject(jsonString);
Iterator keys = questionMark.keys();
while(keys.hasNext()) {
// loop to get the dynamic key
String currentDynamicKey = (String)keys.next();
// get the value of the dynamic key
JSONObject currentDynamicValue = questionMark.getJSONObject(currentDynamicKey);