Java JSON object to read a list value - java

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

Related

How to loop through json arrays nested inside json objects

I have this json text which has some symptoms associated with head diseases:
{
"Head": {
"Agitation": {
"conditions": "Generalized anxiety disorder,Medication reaction or side-effect"
},
"Anxiety": {
"conditions": "Generalized anxiety disorder,Depression (Adult)"
},
"Apathy": {
"conditions": "Depression (Adult),Medication reaction or side-effect,Dementia in head injury"
}
}
}
What I want is to access and display every symptom in this Head block using a for loop, and then access each symptom's conditions and store them separately as arrays.
This java code works but it's functionality is limited:
JSONObject jsonObject = (JSONObject) object;
JSONObject bodyPart = (JSONObject) jsonObject.get("Head");
JSONObject symptoms = (JSONObject) name.get("Agitation");
String res = (String) symptoms.get("conditions");
String[] tokens = res.split(",");
for (int i = 0; i < tokens.length; i++){
System.out.println(tokens[i]);}
Instead of displaying just the conditions of Agitation, how can I display every condition associated with every symptom without having to pass their String values manually into the get methods?
I don't know if I should use JSONArray for "Head" instead of JSONObject to access the symptoms.
Assuming this is the org.json package, you can use JSONObject's keys() method to get an iterator over the object's keys.
Iterator bodyParts = jsonObject.keys();
while (bodyParts.hasNext()){
String bodyPart = (String) bodyParts.next();
JSONObject symptomsJson = jsonObject.getJSONObject(bodyPart);
Iterator symptoms = symptomsJson.keys();
// And so on...
}
My friend, if you're using java, use objects, no plain text, my recommendation is to use Json.simple,
That way you can have List of objects and use the properties you want, take a look on the link examples.

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

To get all the keys in JSONObject into String array

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()

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

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