Get JSON keys with values - java

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

Related

JSONObject start from last key to iterate over the all keys

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

Easiest way to parse a triple nested JSON?

I am given a JSON that will come in this format:
"template":{
"mod1":[
{
"param1":"55",
"param2":"5",
"param3":"somedata"
}
],
"mod2":[
{
"param1":"somedata",
"param2":"somedata"
}
],
"mod3":[
{
"param1":"somedata",
"param2":"somedata",
"param3":"somedata"
}
],
"mod4":[
{
"param1":"somedata",
"param2":"somedata"
}
],
"mod5":[
{
"param1":"somedata"
}
]
}
}
What is the easiest way to parse it? What I'd like is to get the params inside the mod and their associated values together, to store into a database. The way I am doing it is as so:
JSONObject obj = new JSONObject(json);
System.out.println(obj);
Iterator<String> keys = obj.keys();
while(keys.hasNext()) {
String key = keys.next();
JSONObject currTemplate = (JSONObject) obj.get(key);
if(currTemplate instanceof JSONObject) {
System.out.println("LIST OF ALL MODULES : " + currTemplate);
Iterator<String> currObjKeys = ((JSONObject) currTemplate).keys();
while(currObjKeys.hasNext()) {
String currObjKey = currObjKeys.next();
System.out.println("MODULE: " + currObjKey);
JSONArray array = currTemplate.getJSONArray(currObjKey);
System.out.println("ARRAY: " + array);
for(int i = 0; i < array.length(); i++){
JSONObject object = array.getJSONObject(i);
String[] names = JSONObject.getNames(object);
for(String name: names) {
System.out.println("PARAMS");
System.out.println(name);
System.out.println(object.get(name));
}
}
}
}
And it currently prints what I need correctly. What I am asking is if there is a more efficient way to do it - the way I currently have it is O(N^4), and I was wondering if anyone had any idea to parse the JSON in a more efficient way. Note: the params will not always be in form param1, param2, the names will always be different. Just changed it for confidentiality sake.
Thank you in advance.

Parsing Json file and create Hashmap<k,v>

I am finding a solution for get each single key value of a JSONObject dynamicaly.
I have a JSON file like this:
{
"RESPONSE":{
"A":"test",
"B":{
"C":"0",
"D":"1"
},
"E":{
"F":"2",
"G":"3"
}
}
}
I wish to create a Hashmap that contains the key and the value of the objects, like this example:
legend:
key = value
"A" = "test"
"B" = "{"C":"0", "D":"1"}"
"B.C" = "0"
"B.D" = "1"
"E" = "{"F":"2","G":"3"}"
"E.F" = "2"
"E.G" = "3"
I have tried writing this code:
private static HashMap<String, Object> createJsonObjectsHashMapOfConfigFile(String jsonFilePath,
String JsonObjectToIterate) throws Exception {
HashMap<String, Object> jHashMap = new HashMap<>();
JSONObject jsonConfigFile = SimulatorUtil.readJsonFromFile(jsonFilePath); // Returns the Json file
JSONObject jsonConfigObj = jsonConfigFile.getJSONObject(JsonObjectToIterate); // JsonObjectToIterate -->
// "RESPONSE"
Iterator<?> configIter = jsonConfigObj.keys();
String currentDynamicKey = "";
while (configIter.hasNext()) {
currentDynamicKey = (String) configIter.next();
Object currentDynamicValue = jsonConfigObj.get(currentDynamicKey);
jHashMap.put(currentDynamicKey, currentDynamicValue);
logger.info(" ---> " + jHashMap.toString());
}
return jHashMap;
}
but it get only the first level key ("A", "B", "E").
I must use org.json.
Can anyone help me?
Thanks,
Luca

get value by key jsonarray

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!

Json Object - Getting the Key and the Value

I am a newbie to JSON . So If this is a very basic doubt don't scold me . I have a JSON Object Reference and I want to get the Key(Object has only one Key Value Pair) . How do I get it in Java ?
You can use jsonObject.keys() for getting all keys. Then you may iterate over keys to get the first key out of them like :
Iterator<String> keys = jsonObject.keys();
if( keys.hasNext() ){
String key = (String)keys.next(); // First key in your json object
}
json.keys() will give all the keys in your JSONObject where json is an object of JSONObject
Recursively search for a key, and if found, return its value
String recurseKeys(JSONObject jObj, String findKey) throws JSONException {
Iterator<?> keys = jObj.keys();
String key = "";
while (keys.hasNext() && !key.equalsIgnoreCase(findKey)) {
key = (String) keys.next();
if (key.equalsIgnoreCase(findKey)) {
return jObj.getString(key);
}
if (jObj.get(key) instanceof JSONObject) {
return recurseKeys((JSONObject)jObj.get(key), findKey);
}
}
return "";
}
Usage:
JSONObject jObj = new JSONObject(jsonString);
String extract = recurseKeys(jObj, "extract");

Categories

Resources