To get all the keys in JSONObject into String array - java

I want to create a json object from existing json object. For this i want to get all the keys in JSONObject to a String[] array. Is there any default method to get the keys into a String array.
I found there exists a static method here getNames() but it's not working.
I can go over each key using iterator and can construct a keys String array but i want any default method if exists.

To construct JSONObject from other JSONObject you can use constructor that accept JSONObject and array of keys names that should be copied. To do it:
Iterator keysToCopyIterator = firstJSONObject.keys();
List<String> keysList = new ArrayList<String>();
while(keysToCopyIterator.hasNext()) {
String key = (String) keysToCopyIterator.next();
keysList.add(key);
}
String[] kesyArray = keysList.toArray(new String[keysList.size()]);
JSONObject secondJSONObject = new JSONObject(firstJSONObject, );

There is not getNames(), but there is Names()

Related

Using javax/json, how can I add elements to an existing JsonArray?

I read a JSON array from a file but I'd like to add additional entries into the array. How would I go about doing this using the javax.json library?
private String getJson(FileInputStream fis) throws IOException {
JsonReader jsonReader = Json.createReader(fis);
// Place where I'd like to get more entries.
String temp = jsonReader.readArray().toString();
jsonReader.close();
fis.close();
return temp;
}
Preview of the JSON format of the file:
[
{"imgOne": "test2.png", "imgTwo": "test1.png", "score": 123123.1},
{"imgOne": "test2.png", "imgTwo": "test1.png", "score": 1234533.1}
]
The short answer is that you can't. JsonArray (and the other value types) is meant to be immutable. The javadoc states
JsonArray represents an immutable JSON array (an ordered sequence of
zero or more values). It also provides an unmodifiable list view of
the values in the array.
The long answer is to create a new JsonArray object by copying over the values from the old one and whatever new values you need.
For example
// Place where I'd like to get more entries.
JsonArray oldArray = jsonReader.readArray();
// new array builder
JsonArrayBuilder builder = Json.createArrayBuilder();
// copy over old values
for (JsonValue value : oldArray) {
builder.add(value);
}
// add new values
builder.add("new string value");
// done
JsonArray newArray = builder.build();

Java JSON object to read a list value

I have a JSON response something like this:
{
"id_list":["123", "456", "789"],
...
}
I was wondering what I should do if I want use the JSONObject to read such a id list and to return a List<String> of the ids for example. I did not see there's any method in JSONObject can do such thing (ref: http://www.json.org/javadoc/org/json/JSONObject.html). The most possible one might be the JSONArray, but I don't know if I use JSONArray and turn every value in the list to be an JSONObject, how can I read them without keys.
Thank you
You can iterate through the JSONArray and store each value to the list, and return that.
JSONObject jo = new JSONObject(jsonString); //
JSONArray ja = jo.getJSONArray("id_list"); // get the JSONArray
List<String> keys = new ArrayList<>();
for(int i=0;i<ja.length();i++){
keys.add(ja.getString(i)); // iterate the JSONArray and extract the keys
}
return keys; // return the list

How to parse JSON Array and stored in arraylist in java?

I want to parse following JSON array and store in array list.
[{"type":{"Male":"1","Female":"2"}}]
I have tried following code
JSONObject object=getJSONObject(0).getString("type");
Result:
{"Male":"1","Female":"2"}
Here type is the key and others are values.
It comes with comma, quotes.How to store this values are in ArrayList?
Something like the below should do the trick for your JSON. Seeing your JSON I don't see an Array anywhere.
String resultJson; // Assuming this has the JSON given in the question.
JSONObject object = new JSONObject(resultJson);
JSONObject type = object.getJSONObject("type"); //Get the type object.
HashMap<String, Integer> map = new HashMap<String, Integer>(); //Creating the Map
String male = type.getString("male"); //Get the male value
String female = type.getString("female"); //Get the female value
map.put("male", Integer.parseInt(male));
map.put("female", Integer.parseInt(female));
Something like this?
ArrayList<String> list = new ArrayList<String>();
if (jsonArray != null) { //In this case jsonArray is your JSON array
int len = jsonArray.length();
for (int i=0;i<len;i++){
list.add(jsonArray.get(i).toString());
}
}

How to convert String representation of ArrayList to ArrayList

I have an ArrayList, Whom i convert to String like
ArrayList str = (ArrayList) retrieveList.get(1);
...
makeCookie("userCredentialsCookie", str.toString(), httpServletResponce);
....
private void makeCookie(String name, String value, HttpServletResponse response) {
Cookie cookie = new Cookie(name, value);
cookie.setPath("/");
response.addCookie(cookie);
} //end of makeCookie()
Now when i retrieve cookie value, i get String, but i again want to convert it into ArrayList like
private void addCookieValueToSession(HttpSession session, Cookie cookie, String attributeName) {
if (attributeName.equalsIgnoreCase("getusercredentials")) {
String value = cookie.getValue();
ArrayList userCredntialsList = (ArrayList)value; //Need String to ArrayList
session.setAttribute(attributeName, userCredntialsList);
return;
}
String value = cookie.getValue();
session.setAttribute(attributeName, value);
} //end of addCookieValueToSession
How can i again convert it to ArrayList?
Thank you.
someList.toString() is not a proper way of serializing your data and will get you into trouble.
Since you need to store it as a String in a cookie, use JSON or XML. google-gson might be a good lib for you:
ArrayList str = (ArrayList) retrieveList.get(1);
String content = new Gson().toJson(str);
makeCookie("userCredentialsCookie", content, httpServletResponce);
//...
ArrayList userCredntialsList = new Gson().fromJson(cookie.getValue(), ArrayList.class);
As long as it's an ArrayList of String objects you should be able to write a small method which can parse the single String to re-create the list. The toString of an ArrayList will look something like this:
"[foo, bar, baz]"
So if that String is in the variable value, you could do something like this:
String debracketed = value.replace("[", "").replace("]", ""); // now be "foo, bar, baz"
String trimmed = debracketed.replaceAll("\\s+", ""); // now is "foo,bar,baz"
ArrayList<String> list = new ArrayList<String>(Arrays.asList(trimmed.split(","))); // now have an ArrayList containing "foo", "bar" and "baz"
Note, this is untested code.
Also, if it is not the case that your original ArrayList is a list of Strings, and is instead say, an ArrayList<MyDomainObject>, this approach will not work. For that your should instead find how to serialise/deserialise your objects correctly - toString is generally not a valid approach for this. It would be worth updating the question if that is the case.
You can't directly cast a String to ArrayList instead you need to create an ArrayList object to hold String values.
You need to change part of your code below:
ArrayList userCredntialsList = (ArrayList)value; //Need String to ArrayList
session.setAttribute(attributeName, userCredntialsList);
to:
ArrayList<String> userCredentialsList = ( ArrayList<Strnig> ) session.getAttribute( attributeName );
if ( userCredentialsList == null ) {
userCredentialsList = new ArrayList<String>( 10 );
session.setAttribute(attributeName, userCredentialsList);
}
userCredentialsList.add( value );

Name/value pair loop of JSON Object with Java & JSNI

With GWT, how would I go about looping through a JSON object or array, which has been returned via a JSNI method, that I could also extract both name and value pairs per loop?
Are you using JavaScriptOverlay types or JSONObject like types?
So in case of JSONObject like types and assuming data is of type JSONObject
you can do following:
json_string = "{'data':{'key':'test','key2':'test3','key3':'test3'}}"
JSONObject json_data = JSONParser.parseLenient(json_string);
JSONObject data = json_data.get("data").isObject();
Set<String> keys = data.keySet();
for (String key : keys)
{
String value = data.get(key).isString().stringValue();
}

Categories

Resources