Insert String array in JSON plain-text - java

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

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

converting JSON OBJECT to JSON ARRAY

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

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"]}

double quote in json simple

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 "\/"

Gson Array of Strings to JsonArray

I'm using Gson and am trying to add a bunch of string values into a JsonArray like this:
JsonArray jArray = new JsonArray();
jArray.add("value1");
The problem is that the add method only takes a JsonElement.
I've tried to cast a String into a JsonElement but that didn't work.
How do I do it using Gson?
You can create a primitive that will contain the String value and add it to the array:
JsonArray jArray = new JsonArray();
JsonPrimitive element = new JsonPrimitive("value1");
jArray.add(element);
Seems like you should make a new JsonPrimitive("value1") and add that.
See The javadoc
For newer versions of Gson library , now we can add Strings too. It has also extended support for adding Boolean, Character, Number etc. (see more here)
Using this works for me now:
JsonArray msisdnsArray = new JsonArray();
for (String msisdn : msisdns) {
msisdnsArray.add(msisdn);
}
I was hoping for something like this myself:
JsonObject jo = new JsonObject();
jo.addProperty("strings", new String[] { "value1", "value2" });
But unfortunately that isn't supported by GSON so I created this helper:
public static void Add(JsonObject jo, String property, String[] values) {
JsonArray array = new JsonArray();
for (String value : values) {
array.add(new JsonPrimitive(value));
}
jo.add(property, array);
}
And then use it like so:
JsonObject jo = new JsonObject();
Add(jo, "strings", new String[] { "value1", "value2" });
Voila!

Categories