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

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

Related

How to remove empty objects from Json Array

So the json is something like it,
"stores": [
{
"amazon": []
},
{
"flipkart": {
"product_store": "Flipkart",
"product_store_logo": "http://images-api.datayuge.in/image/ZmxpcGthcnRfc3RvcmUucG5n.png",
"product_store_url": "https://price-api.datayuge.com/redirect?id=aHR0cHM6Ly9kbC5mbGlwa2FydC5jb20vZGwvbWktYTEtYmxhY2stNjQtZ2IvcC9pdG1leDl3eHh6M2FtamF0P3BpZD1NT0JFWDlXWFVTWlZZSEVUJmFmZmlkPWFydW5iYWJ1bA",
"product_price": "14999",
"product_offer": "",
"product_color": "",
"product_delivery": "3-4",
"product_delivery_cost": "0",
"is_emi": "1",
"is_cod": "1",
"return_time": "10 Days"
}
},
{
"snapdeal": []
}
]
So the non empty object like flipkart is a JsonObject but all other empty objects are array. So I am so confused about how to remove them.
JSONArray store_array = product_details_json.getJSONObject("data").getJSONArray("stores");
for (int i = 0; i<store_array.length(); i++){
JSONObject store = store_array.getJSONObject(i);
if (!store.getJSONObject(store.keys().next()).has("product_store")){
store_array.remove(i);
}else {
Log.i("Size :",store_array.length()+"");
}
}
But that's not working. I know I am doing this all wrong. Because it has both array and objects so i get the following error
Value [] at amazon of type org.json.JSONArray cannot be converted to JSONObject
Need Help!
I see two problems with your code:
Your JSON structure for "stores" is heterogeneous — some elements have a key that maps to an array and some to an object. That's the immediate cause of the error you are seeing. You can either modify your JSON so everything key maps to an object or code defensively.
When you remove an entry, all subsequent entries move up one space, but since you then increment the loop index i, you skip the entry that just moved into the index you just removed. The easiest way to deal with that is to iterate through store_array in reverse order.
Putting this all together (and assuming you aren't going to change your JSON structure), something like the following (untested) should work:
JSONArray store_array = product_details_json.getJSONObject("data").getJSONArray("stores");
for (int i = store_array.length() - 1; i >= 0; i--){
JSONObject store = store_array.getJSONObject(i);
Object storeData = store.get(store.keys().next());
boolean isValidStore = storeData instanceof JSONObject
&& ((JSONObject) storeData).has("product_store");
if (!isValidStore) {
store_array.remove(i);
}
}

Remove object from json response Android

Hello guys I need your help. How do I remove this from my json response?
[
{
"Woa": [
"Seo",
"Rikjeo",
"JDa"
]
},
"Aha",
"Aad",
"Char"
]
I want to remove this:
{
"Woa": [
"Seo",
"Rikjeo",
"JDa"
]
}
This is what I tried so far:
for (int i = 0; i < array.length(); ++i) {
list.add(array.getString(i));
}
list.remove(0);
But it is still not removed. How do I do that? Any ideas will be greatly appreciated
Edited list.remove(1) to (0)
After removing the item you need to create the JSON again using the list.
list.remove(1);
JSONArray jsArray = new JSONArray(list);
If you want to convert JSONArray to JSON string:
jsArray.toString()
Your list will be updated, not your JSON object.
Why don't you use a JSONparser.
JSONObject obj = new JSONObject(mystring);
obj.remove("entryname");
One problem is that the element you are trying to remove is the first one, and the index of the first element of a JSONArray object is zero.
You are calling list.remove(1) which removes the second element of the array.
The following should be sufficient:
list.remove(0);
... without the stuff prior to it.
If this is not working, then my guess is that you are removing the element too late; i.e. after the JSONArray object has been serialized. However, we need to see more (relevant) code to be sure.
The Android documentation for JSONArray fails to mention that array indexing is zero-based. However, it is. I checked the source code. Furthermore most other Java data structures (arrays, lists etcetera) use zero-based indexing. (A notable exception is Java data structures modelled on the W3C DOM APIs.)
You should make something that's more general so you don't have to modify your code EVERY time the JSON changes. For example:
//here we create the JSONArray object from the string that contains the json data
JSONArray array = new JSONArray(myJsonString);
//here we create a list that represents the final result - a list of Strings
List<String> list = new ArrayList<>();
//here we parse every object that the JSONArray contains
for (int i = 0; i < array.length(); i++) {
//if the current item is an JSONObject, then we don't need it, so we continue our iteration
//this check is not necessary because of the below check,
//but it helps you see things clearly: we IGNORE JSONObjects from the array
if (array.get(i) instanceof JSONObject) {
continue;
}
//if our current object is a String, we add it to our final result
if (array.get(i) instanceof String) {
list.add(array.getString(i));
}
}
you can parse your string to JSONArray, the first element of the array is what you want.
#Test
public void test() {
String str = "[ {\"Woa\": [\"Seo\",\"Rikjeo\",\"JDa\"]},\"Aha\",\"Aad\",\"Char\"]";
try {
JSONArray array;
array = new JSONArray(str);
System.out.println(array);
System.out.println(array.get(0));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
[{"Woa":["Seo","Rikjeo","JDa"]},"Aha","Aad","Char"]
{"Woa":["Seo","Rikjeo","JDa"]}
PASSED: test
You Can one by one remove
while (user_data.length() > 0) {
user_data.remove(user_data.keys().next());
}

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

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

Categories

Resources