JSONObject return empty:false - java

After some researchs, I didn't have found any solutions to this problem:
when I create a JSONObject (org.json) from a file, it return "empty":false. Why does it return this and how can I fix it?
Java:
JSONObject config = new JSONObject(Files.readAllLines(Paths.get("config/maj.json")));
JSON:
{"FyloZ":"0"}
Files.readAllLines is working return the right value.
Thanks!

Files.readAllLines() returns List<String>, not a String.
So actually you are using the following constructor (accepting a single Object parameter):
https://stleary.github.io/JSON-java/org/json/JSONObject.html#JSONObject-java.lang.Object-
Construct a JSONObject from an Object using bean getters
The only getter-style method of a List is isEmpty(), so you get that 'empty: false' thing.
Try the following:
String json = new String(Files.readAllBytes(Paths.get("config/maj.json")), "utf-8");
JSONObject config = new JSONObject(json);
Here we read JSON as bytes, convert them to a string (assuming it's in utf-8) and then create a JSONObject from it.

Related

Using vararg to get data from nested JSON Object returns null

I am trying to return data from a nested JSON Object in a seperate JSON file. For example, my JSON file might look like this
{
"user1": {
"name": "John",
"age": 25,
"job": "developer"
},
"day": "May 2nd 2022"
}
And here is the method that I am using to pull the nested Object
public static Object get(String key, String... objKey) throws Exception {
//create new JSON parser and FileReader
JSONParser parser = new JSONParser();
FileReader jsonFile = new FileReader(path);
//Reads the data in JSON file and assigns to Object jsonData
Object jsonData = parser.parse(jsonFile);
//assigns data to a JSONObject object
JSONObject jsonDataObj = (JSONObject) jsonData;
//checks to see if data is an array
if(jsonDataObj.get(key).getClass().isArray()){
throw new Error("Data is an array and not returnable");
}
if(jsonDataObj.get(key) instanceof JSONArray){
//get JSON Object into JSONObject variable to read from
JSONObject jsonObj = (JSONObject) jsonDataObj.get(key);
//get wanted data from nested JSON Object
Object wantedData = jsonObj.get(objKey);
return wantedData;
} else {
//get data associated with 'key' value in JSON Object
Object wantedData = jsonDataObj.get(key);
return wantedData;
}
} //end get()
When I call the method get() with only one param like get("day") it returns the data in day perfectly fine and nothing goes wrong. The problem is when I call the method and introduce a second argument it returns null.
For example, if I call get("user1", "age") instead of returning 25 is return null. I figured out that it is the vararg parameter that is messing it up since when I change the method parameters to String key, String objKey it works fine. Another thing that i've noticed while debuging is that if I print the vararg it prints a memory address instead of the String passed to the parameter.
If it is of any help; I am using the json-simple library on Maven 1.4

JSON Object empty when creating it from a String

I'm trying to create a JSON Object from a String. The String looks like this: {"case":"getAllProducts"}.
Why is jobj always empty?
String received = textMessage.getText();
System.out.println(received); //{"case":"getAllProducts"} - perfect
JsonObject jobj = new Gson().fromJson(received, JsonObject.class);
System.out.println(jobj); //{} - why empty???
String reqCase = jobj.get("case").getAsString();
I already checked out other articles here where its done exactly like I did. I can't find my problem here..
Instead of
new Gson().fromJson(received, JsonObject.class);
it should be
new Gson().fromJson(received, YourClass.class);
where YourClass is a user defined class having attributes same as the attributes in your JSON.

Find JSON object in JSON array

I have a goal to verify that certain JSON that I've got from RabbitMQ corresponds to one of expected JSONs in an array in a single file.
In other words, I need to verify that this JSON:
{
"networkCode":"network",
"programId":"92000"
}
is present in this JSON array:
[
{
"networkCode":"network",
"programId":"92000"
},
{
"networkCode":"network",
"programId":"92666"
}
]
Thank you very much for help!
Some part of my code
//GET DESIRABLE JSON
String message = new String(delivery.getBody(), StandardCharsets.UTF_8);
JSONObject myJSON= new JSONObject(message);
//GET THE JSON ARRAYS FROM FILE
JSONParser parser = new JSONParser();
Object expectedJSONs= parser.parse(new FileReader("C:\\amqpclient\\src\\test\\java\\tradeDoubler\\ExpectedDTO.json"));
JSONArray expectedArray = (JSONArray) expectedJSONs;
JSONAssert.assertEquals(
myJSON, expectedArray , JSONCompareMode.LENIENT);
Compilation says that cannot resolve this
Exception in thread "main" java.lang.AssertionError: Expecting a JSON array, but passing in a JSON object
Org.json library is quite easy to use.
Example code below:
import org.json.*;
JSONObject obj = new JSONObject(" yourJSONObjectHere ");
JSONArray arr = obj.getJSONArray("networkArray");
for (int i = 0; i < arr.length(); i++)
{
String networkCode = arr.getJSONObject(i).getString("networkCode");
......
}
By iterating on your JSONArray, you can check if each object is equal to your search.
You may find more examples from: Parse JSON in Java
May I suggest you to use the Gson Library?
You can use something like this. But It will throw an exception if the json doesn't match/contains the fields.
Type listType = new TypeToken<ArrayList<YourJavaClassJsonModel>>() {
}.getType();
List<YourJavaClassJsonModel> resultList = gson.fromJson(JsonString, listType);
Hope it may help
You could use a JSON parser to convert the JSON to a Java object (Jackson and GSON are good options), and then check that object.

java segregate output received from json and pass value to another method

I am getting following output on console from the json post request in java using rest api.
{"id":"19494","key":"DF-1079","self":"http://sjira/rest/api/2/issue/19494"}
I need to take just key from this output and pass it on to other method using java.
You can use Gson library for json parsing.
This json library will convert json String to the Object you want. You want keys from it so you can get it parsed to a map and then get key set from it. Pass this key set to other method as per your need.
Code Example
Gson gson = new Gson();
String response= "{\"id\":\"19494\",\"key\":\"DF-1079\",\"self\":\"http://sjira/rest/api/2/issue/19494\"}";
//below line will parse your response to map
Map<String,Object> map = gson.fromJson(response, Map.class);
//get keyset from it pass to some method.
passToSomeMethod(map.keySet())
This keyset will be of type Set. Implementation in method to use it should be accordingly.
Done
You should use entrySet() on json object and populate a List which can be further used as argument in a method or anywhere.
JSONParser parser = new JSONParser();
JSONObject jObj = (JSONObject) parser.parse(postString); // postString contains your response string
List<String> keys = new ArrayList<String>();
for (Entry<String, JsonElement> e : jObj.entrySet()) {
keys.add(e.getKey());
}

Json Iterating using java

Here is my json Object.
{"id":"mrbbt6f3fa99gld0m6n52osge0",
"name_value_list":
{"user_default_dateformat":{"name":"user_default_dateformat","value":"m/d/Y"}},
"module_name":"Users"}
I got id,and module_name through following code.How can i get user_default_dateformat?.
I know it may so simple but I am a newbie in json.
String jsonResponse;
while ((jsonResponse = br.readLine()) != null) {
jsonOutput = jsonResponse;
}
JSONObject job = new JSONObject(jsonOutput);
System.out.println(job);// i can see the same json object
that i showen above.
sessionID = job.get("id").toString();
Exception generating coge
JSONObject job2=new JSONObject(job);
dateFormat = job2.get("user_default_dateformat").toString();
The Eexception is
org.json.JSONException: JSONObject["user_default_dateformat"] not found.
Thanks,
name_value_list is also an Object.
JSONObject job2 = new JSONObject(job.get("name_value_list"));
So there you get
job2.get("user_default_dateformat");
Every {} in your JSON is an object. So for every String you get which is something like {"xy":"za","ab":"cd"} you have to cast it to the JSONObject
Edit for your error:
As you can see in your code the line:
JSONObject job2=new JSONObject(job);
will try to generate a JSONObject out of your JSONObject.
You have to get the JSONObject in your JSONObject.
You want to get the user_default_dateformat which is in your JSONObject:
String name_value_list_string = job.get("name_value_list").toString();
//this string is another json-string which contains the user_default_dateformat
JSONObject name_value_list_object = new JSONObject(name_value_list_string);
//This JSONObject contains the user_default_dateformat but this is also a JSONObject
String user_default_dateformat_string = name_value_list_object.get("user_default_dateformat").toString();
//this String contains the user_default_dateformat JSONString
JSONObject user_default_dateformat_object = new JSONObject(user_default_dateformat_string);
//This JSONObject contains the String values of your user_default_dateformat
if you are using JSONSimple library you can use this:
jsonObject = (JSONObject) new JSONParser().parse(jsonstr);
System.out.println((JSONObject)jsonObject.get("name_value_list"))).get("user_default_dateformat"));
This should give you the required result.

Categories

Resources