Adding empty array to a JSON object - java

I am trying to create a JSON object that looks like the below :
{"filters":
{"defaultOperator":"OR",
"filters":[]}}
What should i add to my JSON object to make a empty array object ??. Cant get my head around an empty array .
tried jo1.put("filters",new Object[0]);. This did not work .
I am testing an API which requires these array filled only in special cases, most of the time its empty. But dont know how to add it. I am creating the entry JSON like
JSONObject jo1 = new JSONObject();
jo1.put("defaultOperator", "OR");
jo1.put("filters","[]");
jo3 = new JSONObject();
jo3.put("filters", jo1);
//Toast.makeText(getApplicationContext(),""+jo3.toString() , Toast.LENGTH_LONG).show();
//json = new GsonBuilder().create().toJson(comment1, Map.class);
httppost.setEntity(new StringEntity(jo3.toString()));

JSONArray jarr = new JSONArray();
jo1.put("filters",jarr);
or all on one line:
jo1.put("filters", new JSONArray());

Related

How do I add a name-value pair to JSONArray

I'm sending a json object to a REST url as :
JSONObject loan=new JSONObject();
loan.put("clientId", "1");
loan.put("productId", "1");
Now I also have to send an array as part of the payload :
{
"clientId": 1,
"productId": 1,
"disbursementData": [
{
"expectedDisbursementDate":"21 December 2018",
"principal":2000,
"approvedPrincipal":2000
}
]
}
How do I send the array disbursementData using the JSONObject as I'm doing with the other elements
I have tried using:
JSONArray arr = new JSONArray();
arr.put("expectedDisbursementDate","21 December 2018");
arr.put("principal", "1000");
arr.put("approvedPrincipal", "1000");
loan.put("disbursementData", arr);
I get the following exception :
The method put(int, boolean) in the type JSONArray is not applicable
for the arguments (String, String).
It appears my issue is with adding a name-value pair to JSONArray. Any help on how I can achieve this?
You have to create a JSONObject, put it in a JSONArray and then add it to your first JSONObject, try the following code:
JSONObject aux=new JSONObject();
aux.put("expectedDisbursementDate","21 December 2018");
aux.put("principal", "1000");
aux.put("approvedPrincipal", "1000");
JSONArray arr = new JSONArray();
arr.put(aux);
loan.put("disbursementData",arr);
Logic would be the same for any library but the syntax will differ. I am using thecom.google.gson library.
Create object to be placed in the array :
JsonObject jsonObj = new JsonObject();
jsonObj.addProperty("expectedDisbursementDate", "21 December 2018");
jsonObj.addProperty("principal", "2000");
jsonObj.addProperty("approvedPrincipal", "2000");
Create the array and add the object to it :
JsonArray jsonArray = new JsonArray();
jsonArray.add(jsonObj);
Add the array to the original json object :
JsonObject loan = new JsonObject();
loan.addProperty("clientId", "1");
loan.addProperty("productId", "1");
loan.addProperty("disbursementData", jsonArray.toString());
JSONArray implements Collection (the json.org implementation from which this API is derived does not have JSONArray implement Collection). And JSONObject has an overloaded put() method which takes a Collection and wraps it in a JSONArray (thus causing the problem). I think you need to force the other JSONObject.put() method to be used:
you try to add below line
loan.put("disbursementData", (Object)arr);
You should file a bug with the vendor, pretty sure their JSONObject.put(String,Collection) method is broken.
You are creating JSONArray, array is not map and doesnt support put(key,value).
You have to use put(int index, Object value), where index is the array index(same as array[index]).
In your case the value should be the JSONObject :
{
"expectedDisbursementDate":"21 December 2018",
"principal":2000,
"approvedPrincipal":2000
}

How to create multiple JSON array to JSON object in servlets

I need to create variable amount of JSON objects and based on the result set from a database query. States retrieving from mysql database. I am saving the response in JSON array but it is saving in multiple JSON objects like that:
jString userid = rs2.getString("state");
JSONObject mainObj = new JSONObject();
JSONArray jsArray = new JSONArray();
jsArray.put(userid );
mainObj.put("states", jsArray);
With this output:
{"states":["karnataka"]}
{"states":["kerala"]}
{"states":["chennai"]}
Can I get output in single JSON object like {"States":"karnataka","kerala","chennai"}?
You probably just got some code structure confused.
Try something like this:
JSONArray jsArray = new JSONArray();
JSONObject mainObj = new JSONObject();
//some kind of loop
{
jString userid = rs2.getString("state");
jsArray.put(userid);
}
mainObj.put("states", jsArray);

Json array inside array retrieve values Android

i m trying to get values from JSONArray inside array, i m able to retrieve whole JSON values into JSONArray successfully but not able to retrieve values inside JSONArray. When i convert JSONArray to JSONObject to get values stored inside JSONArray. It gives error: org.json.JSONException: No value for "banner"
Here is JSON code, i verified JSON code with jsonlint.com and it showed JSON is Validate,
[
{"code":"banner","moduletitle":0,
"banner":
[
{"image":"http://imageurl"},
{"image":"http://imageurl"},
{"image":"http://imageurl"}
]
}
]
I m trying to get this from 3 hour but no luck. i m new in JSON and do not know how JSON Actually work, and also read abut GSON Library to get JSON values. here is My Java code.
JSONArray jsonObj = null;
String image_url = "";
String banner_code ="";
try {
jsonObj =new JSONArray(lib_function.getJSONUrl( jsontags.Top_Banner_JOSN_URLs));
Log.d("value retrun :","" +jsonObj);
//---vlaue is coming and print in Log ----//
} catch (JSONException e) {
Log.v("Error in Parser :", " " + e);
Log.d("no value retrun :", "failed to convert");
}
try{
JSONObject jo = new JSONObject();
JSONArray ja = new JSONArray();
// populate the array
jo.put("arrayName", jsonObj);
JSONArray subArray = jo.getJSONArray("banner");
image_url= subArray.getString(Integer.parseInt("image"));
Log.d("banner code",""+subArray);
}catch(Exception e)
{
Log.d("not working",""+e);
}
I folllow this question but luck:
How to parse JSON Array inside another JSON Array in Android
If anyone suggest, what i m doing wrong will be appreciate. or let me know, where i can get more information about json
UPDATE thanks too all to give their precious time for answering my stupid question. All answers are correct , but i can accept only one answer. A Big thanks to all
Here:
JSONObject jo = new JSONObject();
JSONArray ja = new JSONArray();
// populate the array
jo.put("arrayName", jsonObj);
Because parsing jsonObj JSONArray so no need to create new JSONArray and JSONObject to extract it from jsonObj. remove all above three lines.
banner JSONArray is inside JSONObject which is contained by jsonObj JSONArray, get it as:
JSONObject jsonObject=jsonObj.optJSONObject(0);
JSONArray subArray = jsonObject.getJSONArray("banner");
// get code key from `jsonObject`
String strCode=jsonObject.optString("code");
// get all images urls from `subArray`
for(int index=0;index<subArray.length();index++){
JSONObject imgJSONObject=subArray.optJSONObject(index);
// get image urls
String strImgURL=imgJSONObject.optString("image");
}
Also, if jsonObj JSONArray contains multiple JSONObject's then use for-loop to iterate it.
I am assuming you have the rest of the values accessible to you, so posting just this snippet.
code=jsonObject.getString("code");
moduletitle=jsonObject.getString("moduletitle");
banner=jsonObject.getJSONArray("banner");
jsonObj =new JSONArray(lib_function.getJSONUrl( jsontags.Top_Banner_JOSN_URLs);
From above line you will get JSONArray. So now loop it and get you banner JSONArray.Again loop bannerArray and you will get image Urls
If You want value of "image" which is in json arrray than
String response = "your response";
try{
JsonArray jAry = new JsonArray(response);
JsonObject jObj = jAry.getJsonObject(0);
JsonArray jsonBanner = jObj.getJsonArray("banner");
JsonObject temp;
for(int i=0;i<jsonBanner.length;i++){
temp = jsonBanner.getJsonObject(i);
String image = temp.optString("image");
}
}

Creating json in java getting only first value not getting as desired format

I want to create a json array which looks like follows:
[{"label":"Organisation 1","ID":2},{"label":"Organisation 2","ID":1},....]
I did as follows :
JSONObject obj = new JSONObject();
while (rstcust.next()) {
obj.put("label", rstcust.getString(3));
obj.put("ID", rstcust.getInt(1));
}
out.print(obj);
I am getting only first value as output I am not getting like the fomat above:
I am getting the following output
{"label":"Organisation 1","ID":2}
This is happening because you are creating a JSONObject but what you need is a JSONArray
Create a JSONArray Object and then add individual JSONObjects into it.The code will be something like this.
JSONArray arr = new JSONArray();
while (rstcust.next()) {
JSONObject obj = new JSONObject();
obj.put("label", rstcust.getString(3));
obj.put("ID", rstcust.getInt(1));
arr.put(obj);
}
out.print(arr);
The JavaDocs for JSONArray can be found here.
In java 6 org.json.JSONArray contains the put method and in java 7 javax.json contains the add method.

How to deserialize a jsonarray into a List<Map> in java using flexjson.deserializer?

In the client side, I have constructed a JSOnARRAY like this:
{"filterEntries":[{"dataName":"mainContact","filterValue":"BILLGATES"}]}.
On the server side (java), I can retireve the values using :
jfilter = JSONValue.parse(jsonFilterStr); //jsonFilterStr={"filterEntries":[{"dataName":"mainContact","filterValue":"BILLGATES"}]}.
JSONArray jFilterEntries = (JSONArray) jfilter.get("filterEntries");
for (int i=0;i<jFilterEntries.size();i++){
JSONObject jFilterEntry = (JSONObject) jFilterEntries.get(i);
String dataName = (String) jFilterEntry.get("dataName");
String filterValue = (String) jFilterEntry.get("filterValue");
}
But the existing app is using flex.json.deserializer and I am unable to achieve the same using flex.json.deserializer. How should I proceed?
I wish to do something like this:
JSONDeserializer jsonDeserializer = new JSONDeserializer();
jsonDeserializer.use(null, List.class);
List<Map<String,String>> lMap= (List<Map<String,String>>)jsonDeserializer.deserialize(params);
Remember the top object that wraps the array. You have to handle that as well. You have to tell it to expect a Map inside the List. To do that you have to specify the type contained in the list by using the path expression "values".
Map<String,List<Map<String,String>>> result = new JSONDeserializer<Map<String,List<Map<String,String>>>>()
.use("values",List.class)
.use("values.values", Map.class)
.deserialize( json);
List<Map<String,String>> filterEntries = result.get("filterEntries");
Updated: Add the new keyword, and made the generic types on the right match the left.

Categories