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
}
}
Related
JSONArray arr =
[
{"key1":"value1"},
{"key2":"value2"},
{"key3":"value3"},
{"key4":"value4"}
]
arr.get("key1") throws error. How can I get the value by key in JSONArray?
arr.getString("key1") also throws error. Should I loop through the array? Is it the only way to do it?
What is the error?
In Eclipse Debug perspective, these expressions returns as; error(s)_during_the_evaluation
You can parse your jsonResponse like below code :
private void parseJsonData(String jsonResponse){
try
{
JSONArray jsonArray = new JSONArray(jsonResponse);
for(int i=0;i<jsonArray.length();i++)
{
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
String value1 = jsonObject1.optString("key1");
String value2 = jsonObject1.optString("key2");
String value3 = jsonObject1.optString("key3");
String value4 = jsonObject1.optString("key4");
}
}
catch (JSONException e)
{
e.printStackTrace();
}
}
Sounds like you want to find a specific key from an array of JSONObjects. Problem is, it's an array, so you have to iterate over each element. One solution, assuming no repeat keys is...
private Object getKey(JSONArray array, String key)
{
Object value = null;
for (int i = 0; i < array.length(); i++)
{
JSONObject item = array.getJSONObject(i);
if (item.keySet().contains(key))
{
value = item.get(key);
break;
}
}
return value;
}
Now, let's say you want to find the value of "key1" in the array. You can get the value using the line: String value = (String) getKey(array, "key1"). We cast to a string because we know "key1" refers to a string object.
for (int i = 0; i < arr.length(); ++i) {
JSONObject jsn = arr.getJSONObject(i);
String keyVal = jsn.getString("key1");
}
You need to iterate through the array to get each JSONObject. Once you have the object of json you can get values by using keys
You can easy get a JSON array element by key like this:
var value = ArrName['key_1']; //<- ArrName is the name of your array
console.log(value);
Alternatively you can do this too:
var value = ArrName.key_1;
That's it!
I have been trying to get the key and value of my JSONObject. I have no idea why this isn't working, because String key is clearly a string?
My code:
JSONObject obj = new JSONObject(historie2.getData());
Iterator<?> keys = obj.keys();
while(keys.hasNext()) {
String key = (String)keys.next();
String value = obj.getString(key); //This is where the error comes
}
The JSONObject:
{
"relatie_website": ["www.apple.com"],
"relatie_kvknummer": ["NL3234234"],
"relatie_naam": ["Apple international inc."],
"relatie_d400code": [null],
"relatie_zoeknaam": ["APPLE INC"],
"relatie_debiteurnummer": ["3523523"],
"relatie_btwnummer": ["332342"]
}
This is the error I have been getting:
org.json.JSONException: JSONObject["relatie_website"] not a string.
You should change your object to be sth like that :
{
"relatie_website": "www.apple.com",
"relatie_kvknummer": "NL3234234",
"relatie_naam": "Apple international inc.",
"relatie_d400code": null,
"relatie_zoeknaam": "APPLE INC",
"relatie_debiteurnummer": "3523523",
"relatie_btwnummer": "332342"
}
Because the problem is that your values are an array and not a string.
But if you need te keep your values in an array you can change your code to support the arrays :
JSONObject obj = new JSONObject(historie2.getData());
Iterator<?> keys = obj.keys();
while(keys.hasNext()) {
String key = (String)keys.next();
JSONArray value = obj.getJSONArray(key);
}
And you will have a JsonArray that you can manipulate as you want by doing sth like that :
for (int i = 0; i < value.length(); i++) {
String val = value.getString(i).toString();
logger.info("val : " + val);
}
I am attempting to iterate through a hash map and create a json string from the values. Im using the JSONSimple library to do so. I have the structure I want, but the values are being overwritten. The structure I am ending up with is
{
"new_id":{
"coordinates_list":{
"Coordinates: ":[
"lat: 27.0",
"lon: 28.0"
]
},
"t0vhf40cv86t":[
"123"
]
}
}
But there should be additional values in the JSON. Only the last row of the hash map is being included. Do I need to add another JSONObject that I write to?
JSONObject obj = new JSONObject(); // final json object written out
double lat = 20.00; // test data
double lon = 21.00; // test data
for (Map.Entry<String, List<String>> entry : data.entrySet()){
JSONObject childObj = new JSONObject();
JSONObject coordObj = new JSONObject();
JSONArray entities = new JSONArray();
JSONArray coordinates = new JSONArray();
String key = entry.getKey();
List<String> values = data.get(key);
for(String value : values){
entities.add(value);
}
childObj.put(key,entities);
// increments the test data
lat = lat +1;
lon = lon + 1;
coordinates.add("lat: " + lat);
coordinates.add("lon: " + lon);
coordObj.put("Coordinates: " ,coordinates);
childObj.put("coordinate list ", coordObj);
obj.put("new_id" , childObj);
}
You are always using "new_id" as the key on the "obj.put" line. For the first map entry, you set the value for that key on the JSON object. For each subsequent entry, you are replacing the value for that key, not adding a new key. That is why only the last entry in the map is represented in the JSON.
I'm not sure exactly what you're trying to accomplish, but you likely either need to use a different key each time through the loop or use a JSONArray instead of a JSONObject so that you don't need keys at all.
I have some piece of JSON information.
Example:
"Items":[{"User":{"Id":"123","name":"abcdef","email":"xy#z.com"},"User":{"Id":"456","name":"def","email":"we#z.com"}}]
I want to remove symbols such as '{','"' and '}' and store it in the ArrayList such that each element in the JSON has a separate position in a new ArrayList.
The output i am expecting looks somewhat like this:
ArrayList[0][0]:Id
ArrayList[0][1]:123
ArrayList[1][0]:name
ArrayList[1][1]:abcdef
etc.,
Sample code:
public String[] ParseGetJSON (String str){
String text = str;
try{
JSONParser jsonParser = new JSONParser();
JSONObject jsonObj = (JSONObject) jsonParser.parse(text);
JSONArray item = (JSONArray) jsonObj.get("Items");
for(int i = 0;i<item.size();i++){
System.out.println("The "+i+" element of the array"+item.get(i));
}
The Output:
The 0 element of the array: {"Id":"123","name":"abcdef","email":"xy#z.com"}
The problem you are having is that your original input JSON is nested more deeply than you are parsing. The output you are seeing when you call item.get(i) makes it clear that each element of item is also a JSONObject, each of which has three fields (Id, name, email).
What you want to do is treat each element as the JSONObject it is, and parse it as well:
for(int i = 0;i<item.size();i++) {
// get the next element as a Object and print it
System.out.println("The "+i+" element of the array: "+item.get(i));
// get the next element as a JSONObject
JSONObject obj = item.getJSONObject(i);
Iterator<String> itr = obj.keys();
// print all its keys/value pairs
while (itr.hasNext()) {
String key = itr.next();
String value = obj.getString(key);
System.out.println("key=" + key + ", value=" + value);
// key=email, value=xy#z.com
// key=name, value=abcdef
// key=Id, value=123
// ...
}
}
Once you have extracted each key and value, you can do whatever you want with them.
I am getting this string from a service. I want a map or json out of this. It should look like this.
Map output
Total time taken:226006
nodea:10615
nodez:5308'
String timingTrace = "Total time taken:226006.,"
+ "time spent in nodes:{\"nodea\":{\"timeTaken\":10615},\"nodez\":{\"timeTaken\":5308}}\"";
What I have tried so for is the below code. Can I do something better? Any library that can easily convert the above string to map.
if (timingTrace != null) {
arrayofTimeStamp = StringUtils.splitByWholeSeparator(StringUtils.remove(timingTrace, " "), ".,");
}
String[] totaltime = StringUtils.split(arrayofTimeStamp[0], ":")
Map<String,Object> timestamps = new HashMap<String, Object>();
timestamp.put(totaltime[0], totaltime[1]);
String[] nodetimestamp = StringUtils.splitByWholeSeparator(arrayofTimeStamp[1], "time spent in nodes:");
getMapped(nodetimestamp[1]);
public void getMapped(String json) throws JSONException, ParseException {
JSONObject obj = new JSONObject(json);
Iterator<String> keys = obj.keys();
while (keys.hasNext()) {
String key = keys.next();
String timetaken = JsonPath.read(json, "$." + key + ".timeTaken");
timestamp.put(key, timetaken);
}
}
You are using timestamp Map<> object in function getMapped(String json) that give you error because you haven't passed it you declare in function.
To get output you have mention change write below code instead of function getMapped(String json) :
JSONObject obj = new JSONObject(nodetimestamp[1]);
Iterator<String> keys = obj.keys();
while (keys.hasNext())
{
String key = keys.next();
String timetakenStr = obj.getString(key);
JSONObject child = new JSONObject(timetakenStr);
timestamps.put(key, child.getString("timeTaken"));
}
Using above code your Map<> will contain same what you mention.
OutPut :
{nodea=10615, Total time taken=226006, nodez=5308}