I am wondering if there is a way to get the value of the first child of a JSONObject without knowing its name:
I have some JSON coming in with a node called, this_guy
{"this_guy": {"some_name_i_wont_know":"the value i care about"}}
Using JSONObject, how can I get "the value i care about," cleanly if I don't know the name of the child. All I know is "this_guy", anyone?
Use JSONObject.keys() which returns an iterator of the String names in this object. then use these keys to retrieve values.
To get only first value:
Iterator<String> keys = jsonObject.keys();
// get some_name_i_wont_know in str_Name
String str_Name=keys.next();
// get the value i care about
String value = json.optString(str_Name);
Object obj = parser.parse(new FileReader("path2JsonFIle"));
JSONObject jsonObject = (JSONObject) obj;
try this iterator
JSONObject jsonObj = (JSONObject)jsonObject.get("this_guy");
for (Object key : jsonObj.keySet()) {
//based on you key types
String keyStr = (String)key;
Object keyvalue = jsonObj.get(keyStr);
/*check here for the appropriate value and do whatever you want*/
//Print key and value
System.out.println("key: "+ keyStr + " value: " + keyvalue);
}
once you get the appropriate value, just break out of the loop. for example you said that all you need is the first value in the inner map. so try womething like
int count = 0;
String valuINeed="";
for (Object key : jsonObj.keySet()) {
//based on you key types
String keyStr = (String)key;
Object keyvalue = jsonObj.get(keyStr);
valueINeed = (String)keyvalue;
count++;
/*check here for the appropriate value and do whatever you want*/
//Print key and value
System.out.println("key: "+ keyStr + " value: " + keyvalue);
if(count==1)
break;
}
System.out.println(valueINeed);
if you care only about the value and not about the key, you can use directly this:
Object myValue = fromJson.toMap().values().iterator().next();
Related
I have this function:
playerList.forEach(pl ->{
JSONObject player = (JSONObject) pl;
System.out.println(player.get("UUID")+" : " + uuid+" :")
but there is an error on the line "return warps" that say "Unexpected return value".
Why is this happening?
Like what am9417 mentioned, your return statement is inside the forEach scope which is a void function, hence the error you're getting.
Here are two options you can try and play around with:
Using streams. Here I used filter to get the item/s which matches the uuid criteria(argument in your example method). And then findFirst at the end to always get the first occurrence assuming you're expecting 1 UUID match all the time.
// using findFirst returns an Optional type.
Optional<JSONObject> optionalPlayer = playerList
.stream()
.filter(pl -> {
JSONObject player = (JSONObject) pl;
System.out.println(player.get("UUID") + " : " + uuid + " :");
return player.get("UUID").equals(uuid);
}).findFirst();
if (optionalPlayer.isPresent()) {
return (JSONArray) optionalPlayer.get().get("warps");
}
Using a simple for loop:
JSONArray playerList = (JSONArray) obj;
for (Object pl: playerList) {
JSONObject player = (JSONObject) pl;
System.out.println(player.get("UUID") + " : " + uuid + " :");
if (player.get("UUID").equals(uuid)) {
return (JSONArray) player.get("warps");
}
}
You are returning the warps inside an anonymous function (ForEach for playerList) so the signature for ForEach does not match, which gives the error.
You should use most likely filter and suitable terminator for your stream. Then just return the collected JSONArray from your getWarps method.
I have the following and I can print out each property. Easy enough, but is there an easy way to print the key and value of each item in the JSON string? Simply looking to print in console the key and the value.
private static void deserializeUserSimple() {
String userJson = "{\"name\":\"smithy\",\"email\":\"blah#gmail.com\",\"age\":21,\"isDeveloper\":true}";
Gson gson = new Gson();
UserSimple userSimple = gson.fromJson(userJson, UserSimple.class);
// this prints but looking for easy way to print all key and values
System.out.println(userSimple.name);
}
String userJson = "{\"name\":\"smithy\",\"email\":\"blah#gmail.com\",\"age\":21,\"isDeveloper\":true}";
JsonObject convertedObject = new Gson().fromJson(userJson, JsonObject.class);
for(String key:convertedObject.keySet()){
System.out.println("Key - " + key);
System.out.println("Value - " + convertedObject.get(key));
}
Output:
Key - name
Value - "smithy"
Key - email
Value - "blah#gmail.com"
Key - age
Value - 21
Key - isDeveloper
Value - true
I have been searching all over, but I still cannot find a solution to my problem. If there is a post made already, please tell me so I can visit it. I have seen similar posts, but they follow a different JSON format than mine, so I wanted to see if it is possible and how it is possible to make it using the JSON format that will be introduced below.
Basically, what I am trying to do is get every element in a JSON file, and retrieve each element's key name and value. Both the key and the value are String values. Here is an example JSON of how I want my JSON code to look like:
{
"Variable1":"-",
"Variable2":" Test "
}
I am using the org.json library, and I would like to know if this is possible, and if it is, how can I achieve it? What I tried to do originally was put the variables under an array named "Variables", but every time I tried getting that array, it gave me an error saying that JSONObject["Variables"] is not a JSONArray. Not sure if this is caused because of a problem in the JDK or because of a problem in my code. That is, of course, a thing to discuss in another thread. So far, this is what I have (FilePath is a String variable that contains the full path to the file):
String Contents = new String((Files.readAllBytes(Paths.get(FilePath))));
JSONObject JsonFile = new JSONObject(Contents);
JSONArray VariableList = JsonFile.getJSONArray("Variables");
for (Object Item: VariableList) {
Map.Entry Item2 = (Map.Entry)Item;
System.out.println("Key: " + Item2.getKey() + ", Value: " + Item2.getValue());
}
The above code should be working if the JSON looked something like this (yes, I said should because it does not work):
{
"Variables": {
"Variable1":"-",
"Variable2":" Test "
}
}
If it is possible, how would I be able to make get the key and value using the first JSON format? If not possible, then how would I do it in an alternative way? Keep in mind, the key name is never going to the same, as the key and value will be different depending on what the user wants them to be, so that is why it is important to be able to loop through every element and get both it's key and value.
Thank you for your time and effort.
"Variables" : { ... } is a JSONObject and not a JSONArray.
For package org.json
try {
String contents = "{\"Variables\":{\"Variable1\":\"-\",\"Variable2\":\" Test \"}}";
JSONObject jsonFile = new JSONObject(contents);
JSONObject variableList = jsonFile.getJSONObject("Variables"); // <-- use getJSONObject
JSONArray keys = variableList.names ();
for (int i = 0; i < keys.length (); ++i) {
String key = keys.getString(i);
String value = variableList.getString(key);
System.out.println("key: " + key + " value: " + value);
}
} catch (Exception e) {
e.printStackTrace();
}
For package JSON.simple
String contents = new String((Files.readAllBytes(Paths.get(FilePath))));
JSONObject jsonFile = new JSONObject(contents);
JSONObject variableList = jsonFile.getJSONObject("Variables"); // <-- use getJSONObject
variableList.keySet().forEach(key -> {
Object value = jsonObj.get(key);
System.out.println("key: "+ key + ", value: " + value);
});
this is my json string for example :
{"data":{ "name":"Red Sox win 7-0!","famil":"INSERT TITLE HERE","tel":"2251472"}}
this is the code I write but it couldn't get the values:
JSONObject jsons = new JSONObject(myString);
Iterator<?> keys = jsons.keys();
String out = "";
while (keys.hasNext()) {
String key = (String) keys.next();
out += key + ": " + jsons.getString(key) + "\n";
}
How can I get each item's value ?
try this code.
JSONObject object = new JSONObject(myString);
JSONObject objectData = object.getJSONObject("data");
String strTel = objectData .optString("tel");
String strFamil = objectData .optString("famil");
String strName = objectData .optString("name");
In your case you can use jsons.getString(key) for each key because your JSONObject contains only Strings.
But in general, JSONObject can contain values of different types: integer, boolean, int/long, double JSONArray and JSONObject. You have to use the right .getSomething() for each one or generat .get() that retuns Object.
Great example json-simple-example-read-and-write-json
This is my JSON string,
{
"listmain":{
"16":[{"brandid":"186"},{"brandid":"146"},{"brandid":"15"}],
"17":[{"brandid":"1"}],
"18":[{"brandid":"12"},{"brandid":"186"}],
}
}
I need to get values in "16","17","18" tag and add values and ids("16","17","18") to two ArrayList.
What i meant is,
when we take "16", the following process should happen,
List<String> lsubid = new ArrayList<String>();
List<String> lbrandid = new ArrayList<String>();
for(int i=0;i<number of elements in "16";i++) {
lsubid.add("16");
lbrandid.add("ith value in tag "16" ");
}
finally the values in lsubid will be---> [16,16,16]
the values in lbrandid will be---> [186,146,15]
Can anyone please help me to complete this.
Use JSONObject keys() to get the key and then iterate each key to get to the dynamic value.
You can parse the JSON like this
JSONObject responseDataObj = new JSONObject(responseData);
JSONObject listMainObj = responseDataObj.getJSONObject("listmain");
Iterator keys = listMainObj.keys();
while(keys.hasNext()) {
// loop to get the dynamic key
String currentDynamicKey = (String)keys.next();
//store key in an arraylist which is 16,17,...
// get the value of the dynamic key
JSONArray currentDynamicValue = listMainObj.getJSONArray(currentDynamicKey);
int jsonrraySize = currentDynamicValue.length();
if(jsonrraySize > 0) {
for (int i = 0; i < jsonrraySize; i++) {
JSONObject brandidObj = currentDynamicValue.getJSONObject(i);
String brandid = brandidObj.getString("brandid");
System.out.print("Brandid = " + brandid);
//store brandid in an arraylist
}
}
}
Source of this answer