JAVA - Convert keys JSONObject to lower case - java

I have a problem related to the keys of a JSONObject. I need to change the keys to lowercase, but I'm not getting it, what's the best way to do this?

Which package is your JSONObject from? If it is from javax.json then it is immutable, hence you need to instantiate a new JSONObject instance and import modified key value pairs into the new instance (from JSONObject Java doc).

Related

How to copy all the values from one JSONObject to another?

I understand that it's perfectly possible to copy each individual component over one by one, but it's extremely messy to do and rather ugly. Isn't there a simpler way to copy all the values from one JSONObject to another? Important to note, I am using json-lib. I'm not opposed to switching tools if it's absolutely necessary. Point is, this is a rather inefficient way of doing things.
After hours of searching, I finally found the answer. I'm sort of embarrased that it's this simple.
~
Json-lib has a beautiful feature that allows you to take your current JSONObject and parse the entirety of the JSONObject into a String. And there already exists a method to build a JSONObject from a String. Therefore, all you need to do is turn the JSONObject into a String, and then back into a JSONObject. You could store the string as a variable (or use it as a return value), then simply take your preexisting JSONObject reference and use the method to rebuild the JSONObject from the String. Simple as that.
EDIT - thought I would give a quick code example
JSONObject a = /* pretend a has 100 elements inside */
String temp = a.toString();
JSONObject b = JSONObject.fromObject(temp);
String temp2= b.toString();
if(temp.equals(temp2)){System.out.println("Well done.");}

javax.json objects have same methods, but they're not implementations of a common interface. How to cast?

I'm dealing with the strange javax.json library. So here's the problem:
I need to cast an Object of type JsonValue to either JsonObject or JsonArray so I can call the methods getJsonObject and getJsonArray of it. Both JsonArray and JsonObject have the same method names with the same functionalities but they're not implemented methods, they are methods defined on each of them! See: JsonObject, JsonArray.
The obvious solution would be to verify the type and then cast depending on the verified type, like this:
if (current.getValueType().equals(JsonValue.ValueType.OBJECT)) {
current = ((JsonObject) current).getJsonObject(node);
} else if (current.getValueType().equals(JsonValue.ValueType.ARRAY)) {
current = ((JsonArray) current).getJsonObject(node);
}
but it'd require too many repetitions on my code. So I ask:
1) If both JsonObject and JsonArray have the same methods, why they're not implementations of some interface?
2) Is there a more elegant way to cast the object to JsonObject or JsonArray at the same time by using some trick? Do you know any way to make this situation better?
Although the 2 methods on the 2 different objects have the same name, their signatures are in fact different. JsonObject#getJsonObject(String) accepts a String key identifying the value to pull from a JSON object of key-value pairs. JsonArray#getJsonObject(int) accepts an int index identifying which element to pull the value from in a JSON array.
In this case, there is no appropriate common interface that the 2 classes can share. Your code will have to know whether to inspect a JSON object or a JSON array and cast accordingly.
Since the 2 methods in question do not have the same signature, there are not other alternatives for calling them in a "common way". You could potentially use reflection, but this risks making the code more confusing. For example, Apache Commons includes MethodUtils#invokeMethod. You could potentially use that to invoke any method named "getJsonObject", accepting any kind of object (either String or int). Although using this would make it "common code" across both cases, it's potentially confusing for people reading the code later. They'd have to keep track of the fact that this is using reflection, and that the passed argument might be either String or int, and that it really all works out thanks to it being either a JSON object or array. Instead, I would favor just doing the downcast in this case.
Chris is right, Your code will have to know whether to inspect a JSON object or a JSON array and cast accordingly. However, if you are ok with adding an external library, I would recommend gson for parsing Json
This library has JsonElement class which should fit good in your case. look at this to see how it works

Java -JsonArray.contains(string) no such function?

I have a JSONArray called playtitles, and a String called playname.
I want to iterate through the JSONArray and check for the String, but JSONArray doesn't have a .contains() function, this is the relevant code:
This is the error I get The method contains(String) is undefined for the type JSONArray
I have tried converting playName to a JSON string but that doesn't seem to work either.
I have also tried using an ArrayList and then converting it to a JSONArray but that causes more problems.
Any tips?
I think you need to use the following implementation:
http://json-lib.sourceforge.net/
According to their specification, there is a .contains() method for JSONArray.
http://json-lib.sourceforge.net/apidocs/net/sf/json/JSONArray.html#contains(java.lang.Object)
So the import would be something like :
import net.sf.json.JSONArray;
Assuming you are using org.json.JSONArray:
Yes, no such method. You will need to implement it yourself.

Java - how to parse both json arrays and objects

i am using the org.json package in Java (Android) and I am just stumbled with a simple problem.
The webserver returns an array if everything is okay, but an json object { error : true, ...} if something went wrong.
How can I parse that into a common object - I mean both arrays and objects are json after all, but it seems JSONArray and JSONOBject don't share an interface in common.
Am I missing something?
Use JSONTokener.nextValue() and check if the result is a JSONObject or a JSONArray (using instanceof).
The real answer is ... fix the webserver and have it return a consistant result. Otherwise, you basically are going to have to manually inspect the returned data to see what it is.
Another option is catching the JSONException the constructor for JSONArray will throw when it isn't an array which would indicate to you that you should try JSONObject.

List<String> to Json String

How can I convert a List to a Json String?
I have managed to do it the other way round, but not this way.
I also don't know how I can specify the names of the keys then..
You can use the Gson Library.
List<String> list;
String json = new Gson().toJson(list);
Edited:
Just to have the complete answer here: The problem is that you are converting the json String into a List<String>. This way you are losing the relation key-value. The correct should be convert the json string into a HashMap<>.
It seems like your real problem is that when you originally turned the JSON string into a List, you threw away the keys. And that is not surprising, a List is not a natural representation of a JSON object (i.e. a thing with key - value pairs). You probably should have represented it as a Map.
But anyway, if you threw away the keys you've go a problem. You need to either you change your data structure to not throw the keys away, or reconstruct the JSON by inferring what the keys should be based on (for instance) their position in the list. (The latter could be a bit dodgy because the order of the name/value pairs in the original JSON should not signify anything ... and could be "random" or "implementation dependent".

Categories

Resources