converting JSON OBJECT to JSON ARRAY - java

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

Related

How to set array in jsonobject

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

Unable to create same parameter value twice in json array

In this code, I am trying to creating something like this-
public String KLYA_JSON_LookUp_MultiNode(String KLYA_To,String KLYA_DLRURL,String KLYA_To2) {
JSONObject jsonObj = new JSONObject();
jsonObj.put("dlrurl", KLYA_DLRURL);
JSONArray array = new JSONArray();
JSONObject Array_item = new JSONObject();
Array_item.put("to", KLYA_To);
Array_item.put("to", KLYA_To2);
array.add(Array_item);
jsonObj.put("lookup", array);
CreatedJson = jsonObj.toString();
System.out.println(CreatedJson);
return CreatedJson ;
}
Output:
{"lookup": [{
"to": "890XXXXXXX"
}, {
"to": "890XXXXXXX"
}], "dlrurl": "http://www.example.com/dlr.php/......"
}
but I dont get as per the above comment, it ends up printing only one to in the array where as it should print two.
Insert
array.add(Array_item);
Array_item = new JSONObject();
between the two calls to Array_item.put.
So after Thomas and Petter's suggestion, I worked on it and this is how it got resolved.
JSONObject jsonObj = new JSONObject();
JSONArray array = new JSONArray();
JSONObject Array_item = new JSONObject();
JSONObject NextArray_item = new JSONObject();
jsonObj.put("dlrurl", "url");
NextArray_item.put("to","XXXX");
Array_item.put("to", "XXX");
array.add(Array_item);
array.add(NextArray_item);
jsonObj.put("lookup", array);
CreatedJson = jsonObj.toString();
System.out.println(CreatedJson);

Creating JSONArray from JSONObjects

I have json libs (json-simple) and trying to make jsonarray from jsonobjects.
My aim to make JSON string look something like string below
[{"name": "somename","surname": "somesurname"},
{"name": "somename2","surname": "somesurname2"}]
and it will have possibility of adding new objects in the same array.
This what im "hardcoding" now.
JSONObject obj= new JSONObject();
JSONArray arr = new JSONArray();
for(int i = 0 ; i< arr.size() ; i++)
{
obj.put("name", name);
obj.put("surname", surname);
arr.add(obj);
obj= new JSONObject();
}

Convert a string which has JSON into list and then add that list into JSON back

Here, I have a String which has JSONObject inside it like this :
String a = "{"company_name":"ABC","company_address":"hgfh"}";
I added this JSONObject into String with this code :
JSONObject company_one1 = new JSONObject();
company_one1.put("company_name", cmpy_name.getText()
.toString().trim());
company_one1.put("company_address", cmpy_addrs.getText()
.toString().trim());
a = company_one1.toString();
But now I've only the String and I need to add the JSONObject of this String a into an ArrayList and then convert that ArrayList into JSON which should look like :
{"id":"5","data":[{"company_name":"ABC","company_address":"hgfh","image":["cmFodWxtaXNocmE="]}]}
I have tried lots of things to change format like this, but I'm not getting exact format. Sometimes it adds backslashes \ itself into JSON beacuse we can't create a JSON which is already a JSON.
Please give me a proper solution for it.
Thanks in advance.
try this,
JSONArray imageArray = new JSONArray();
imageArray.put("cmFodWxtaXNocmE=");
//* you can add more to the image array by using the put method
JSONObject company_one1 = new JSONObject();
company_one1.put("company_name", cmpy_name.getText()
.toString().trim());
company_one1.put("company_address", cmpy_addrs.getText()
.toString().trim());
//* add the image array
company_one1.put("image", imageArray);
//* create a JSONArray for company types,
JSONArray dataArray = new JSONArray();
dataArray.put(company_one1);
//* you can add more to the array here by using the put method
//* now put all in one main JSONObject
JSONObject mainObj = new JSONObect();
mainObj.put("id", "5");
mainObj.put("data", dataArray);
String finalJsonString = mainObj.toString();
I don't think you are handling with JSON in a right wary. Maybe you should do like this:
try {
Map<String, String> map1 = new HashMap<String, String>();
map1.put("company_name", "company_name");
map1.put("company_address", "company_address");
Map<String, String> map2 = new HashMap<String, String>();
map2.put("company_name", "company_name");
map2.put("company_address", "company_address");
Map<String, String> map3 = new HashMap<String, String>();
map3.put("company_name", "company_name");
map3.put("company_address", "company_address");
List<Map<String, String>> list = new ArrayList<Map<String, String>>();
list.add(map1);
list.add(map2);
list.add(map3);
JSONArray jsonArray = new JSONArray(list);
JSONObject jsonObject1 = new JSONObject();
jsonObject1.put("id", "5");
jsonObject1.put("data", jsonArray);
} catch (JSONException e) {
e.printStackTrace();
}
Here is the link, if you wish to use GSON as library to serialize and de-serialize json data. Visit Tutorail Java Object to/from JSON and library Gson
Here is pseudo code.(so it could not be compiled maybe)
But Gson is pretty easy and useful.
class Company {
String name;
... // constructors, getter/setters...
}
class CompanyGroup {
int id;
List<Company> companies;
... // constructors, getter/setters...
}
String name = "ABC";
Company a = new Company(name);
int id = 5;
CompanyGroup g = new CompanyGroup(5);
g.companies.add(a);
String r = new Gson().toJson(g);
System.out.println(r);
// I/System.outīš• {"companies":[{"name":"ABC"}],"id":5}

JSON - Create JSONObject with array

I need to create in a Java (Android) a JSONObject/JSONArray with the exact following structure:
{
"listId":
[
"c02bc683-fcd7-47a5-b157-853e26ed099e",
"f8e1c9d7-ae45-4433-a315-726c1d912d09"
]
}
Can somebody help me on this please?
EDIT:
What i have is this:
JSONArray obj = new JSONArray();
JSONObject jsonObject = new JSONObject();
jsonObject.put("listId", folderId);
obj.put(jsonObject);
JSONObject json = new JSONObject();
json.put("id", obj);
But this produces something like:
{
"listId":
[
{"id":"c02bc683-fcd7-47a5-b157-853e26ed099e"},
{"id":"f8e1c9d7-ae45-4433-a315-726c1d912d09"}
]
}
Thanks
You've got your array creation a bit mixed up. What you really want is an object holding an array of string, but what you're doing is creating an array of JSONObject.
Try this instead:
String[] arr = { "c02bc683-fcd7-47a5-b157-853e26ed099e", "f8e1c9d7-ae45-4433-a315-726c1d912d09" };
JSONArray jsonArray = new JSONArray(arr);
JSONObject json = new JSONObject();
json.put("listId", jsonArray);
System.out.println(json); // {"listId":["c02bc683-fcd7-47a5-b157-853e26ed099e","f8e1c9d7-ae45-4433-a315-726c1d912d09"]}

Categories