Unable to set array inside JSONObject according to the response.Below is my code in which I am unable to set array in jsonobject. How to send key value for array inside my jsonobject for which shared the response which code is getting from postman
Is this the right way in code
Code--
JsonArray array = new JsonArray();
array.add(productId);
array.add(qty);
JSONObject jsonObject = new JSONObject();
jsonObject.put("productDetails", array);**
This is the code in MainActivity. The problem is not getting correct jsonarray in my JSON object so API will not hit correctly
These String key values are used to pass in request params
String key="WSEoaGBifOEIS5dd6vQ5tfbs3R1c8Rsz";
String affId="teamfotog";
String act="photoStores";
String latitude="40.7127753";
String longitude="-74.0059728";
String devinf="Android,7.0";
String appver="1.00";
String productId="6670002";
String qty="3";
//productDetails
**JsonArray array = new JsonArray();
array.add(productId);
array.add(qty);**
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("apiKey", key);
jsonObject.put("affId", affId);
jsonObject.put("act", act);
jsonObject.put("latitude", latitude);
jsonObject.put("longitude", longitude);
jsonObject.put("devinf", devinf);
jsonObject.put("appver", appver);
**jsonObject.put("productDetails", array);**
JsonParser jsonParser = new JsonParser();
ApiStorePhotoInterface apiInterface = ApiStorePhotoClient.getApi();
Call<PhotoStoreMainModel> call = apiInterface.getResponse((JsonObject) jsonParser.parse(jsonObject.toString().trim()));
Request Params is in Jsonbody --
{"apiKey":"WSEoaGBifOEIS5dd6vQ5tfbs3R1c8Rsz","affId":"teamfotog","act":"photoStores","latitude":"40.7127753","longitude":"-74.0059728","devinf":"Android,7.0","appver":"1.00","productDetails":[{"productId":"6670002","qty":"3"}]}
Of course, it won't work. You are directly adding objects(Strings) in your JsonArray. In the response body, what you really want is a JsonObject inside the JsonArray. Try this -
JsonObject productDetail = new JsonObject();
productDetail.addProperty("productId", productId);
productDetail.addProperty("qty", qty);
JsonArray array = new JsonArray();
array.add(productDetail);
Try this .
jsonObject.put("productDetails",(Object)array);
If someone is still having problems with this, this is what fixed it for me:
Use:
JSONArray
istead of
JsonArray
You should put product detail model to array
String key="WSEoaGBifOEIS5dd6vQ5tfbs3R1c8Rsz";
String affId="teamfotog";
String act="photoStores";
String latitude="40.7127753";
String longitude="-74.0059728";
String devinf="Android,7.0";
String appver="1.00";
String productId="6670002";
String qty="3";
JsonObject product = new JsonObject();
product.put("productId",productId);
product.put("qty",qty);
JsonArray array = new JsonArray();
array.add(product);
JSONObject jsonObject = new JSONObject();
jsonObject.put("apiKey", key);
jsonObject.put("affId", affId);
jsonObject.put("act", act);
jsonObject.put("latitude", latitude);
jsonObject.put("longitude", longitude);
jsonObject.put("devinf", devinf);
jsonObject.put("appver", appver);
jsonObject.put("productDetails", array);
Related
This is very simple one but struggeling. help me out of this.
I am having a json data { "abc":"test","bed":"cot","help":"me"}
I want to convert above jsonObject into JSON ARRAY like [{ "abc":"test","bed":"cot","help":"me"}]
JSONObject obj= new JSONObject(str.toString());
Iterator x = obj.keys();
JSONArray jsonArray = new JSONArray();
Map<String, String> map = new HashMap<String, String>();
while (x.hasNext()) {
for(int i=0;i<obj.length();i++) {
LOG.info("=============");
String key = (String) x.next();
jsonArray.put(obj.get(key));
}
}
I am getting only values. Please help me solve this.
Directly put JsonObject i.e. obj into jsonArray
jsonArray.put(obj);
//result is [{ "abc":"test","bed":"cot","help":"me"}]
Final code
JSONObject obj= new JSONObject(str);
JSONArray jsonArray = new JSONArray();
//simply put obj into jsonArray
jsonArray.put(obj);
//result is [{ "abc":"test","bed":"cot","help":"me"}]
It works for me.
JSONObject obj = new JSONObject(result.toString());
JSONArray arr = obj.getJSONArray("value");
I've created some JSON strings in Java but I don't know how to insert string array.
For example, I've want to add string the format is:
String aux1 = "{ \"key\" : \"value\"};
But if i want to add as value: new String[] {"string1", "string2"};
How I can represent a string array in text-plain format??
Thanks
Use the JSONObject class :
JSONObject object = new JsonObject();
object.put("key1", "value1");
object.put("key2", "value2");
String jsonString = object.toString(); //This will create the corresponding JSON-formatted string
You can use something like this:
String[] strArray = new String[] {"string1", "string2"};
JSONObject jo = new JSONObject();
jo.put("key", Arrays.asList(strArray));
Output would be:
{"key":["string1","string2"]}
String[] strArray = new String[] {"string1", "string2"};
String str1 = Arrays.toString(strArray);
JSONObject jobj = new JSONObject();
jobj.put("yourstringKey",str1);
you can do above way only if your strArray size is more(supose greater than 10.) But if your array is small.then use following way.
JSONObject jobj1=new JSONObject();
jobj1.put("key1","value1");
jobj1.put("key2","value2");
JSONObject jobj=new JSONObject();
jobj.put("mystring",jobj1.toStirng());
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");
}
}
I need to transform my data in a ArrayList to a JSON file, and I use JSON.simple. Everything is fine except one little thing that I want to get a result like ...... {source:0, target:1},{source:0, target:1},{source:0, target:2},{source:0, target:3} ...... but it returns ......{source:0, target:16},{source:0, target:16},{source:0, target:16}...... . My solution.size() is 17.
Here is my code:
JSONObject jsonObject = new JSONObject();
JSONObject jsonNodesObject = new JSONObject();
JSONObject jsonEdgesObject = new JSONObject();
JSONArray jsonNodesArray = new JSONArray();
JSONArray jsonEdgesArray = new JSONArray();
String instString = solutions.get(0).get("institution");
jsonNodesObject.put("name", instString);
// extract name and institution from ArrayList
for (int i = 0; i < solutions.size(); i++)
{
HashMap<String, String> eleHashMap= solutions.get(i);
String nameString = eleHashMap.get("name");
jsonNodesObject.put("name", nameString);
jsonNodesArray.add(jsonNodesObject);
jsonEdgesObject.put("source", 0);
jsonEdgesObject.put("target", i);
jsonEdgesArray.add(jsonEdgesObject);
}
jsonObject.put("nodes", jsonNodesArray);
jsonObject.put("edges", jsonEdgesArray);
System.out.println(jsonObject);
It seems that in every for loop, it refreshes the value of target: i of all my jsonEdgesArray.
Dose anyone know how to fix this? Thanks in advance!
As your iterating jsonNodesObject in for loop, same value will be put for jsonNodesObject.put("name", nameString); u have to initialize JSONObject jsonNodesObject = new JSONObject(); inside for loop
I want this outcome:
{"link":[{"url":"http://en.wikipedia.org/wiki/JScript", "label":"wikipedia"}]}
I tried this:
JSONObject ob1 = new JSONObject();
ob1.put("link","[{\"url\":\"http://en.wikipedia.org/wiki/JavaScript\", label:\"wikipedia\"}]");
The output of ob1.toJSONString() is:
{"link":"[{\"url\":\"http:\/\/en.wikipedia.org\/wiki\/JavaScript\", label:\"wikipedia\"}]"}
What am I doing wrongly?
I am using json-simple-1.1.1
You should put a JSONArray into the JSONObject and in the Array again a JSONObject with the keys/values "url"/"http://en.wikipedia.org/wiki/JScript" and "label"/"wikipedia"
JSONObject ob1 = new JSONObject();
JSONArray ar1 = new JSONArray();
ob1.put ("link", ar1);
JSONObject ob2 = new JSONObject();
ar1.add(ob2);
ob2.put("url", "http://en.wikipedia.org/wiki/JScript");
ob2.put("label", "wikipedia");
In case you have the value of ob1 link object already as JSON string then you can first interpret this into a JSONArray using
JSONArray ar1 = (JSONArray)JSONValue.parse(yourJSONStr);
NOTE: Your intended result is not a JSON string, because for that all "/" must be escaped "\/"