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!
Related
I have a JSON Object which I created from a .json file which looks like the follownig:
{
"key1": {
"key2": "value2",
"key3": "value3",
}
}
To generate the JSON-Object I use:
JSONObject newJSON = new JSONObject(content);
What I want to do, is to generate a String array, which contains all keys of the existing JSONObject, to easily access them.
JSONObject implements the Map interface, so you can use the same way you'd use for Map to generate the list of keys. In particular, you can use the .keySet() or .entrySet() method.
For example (adapted from here):
JSONObject jsonObj = ...;
List<String> l = new ArrayList<String>(jsonObj.keySet());
You could iterate through the keys.
JSONObject newUserJSON = new JSONObject(content);
ArrayList<String> keys = new ArrayList<>();
String key;
for (Iterator<String> it = newUserJSON.keys(); it.hasNext(); ) {
key = it.next();
keys.add(key);
}
And also you need to take care of nested json Object for each key.
Answer to this question is already available in another SO thread: Convert string to JSON array
Here's the equivalent for your use case:
JSONObject jsnobject = new JSONObject(content);
JSONArray jsonArray = jsnobject.getJSONArray("key1");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject explrObject = jsonArray.getJSONObject(i);
}
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 have to make a file in JSON format which must look like the following:
xyz.json
[
{
"imagelist": "/oracle/public/oel6",
"label": "test_higgs",
"shape": "small",
"name" : "/Compute-computecli1/computeadmin/",
"networking" : {
"eth0" : {
"ipnetwork" : "/Compute-computecli1/computeadmin/ipnet"
}
}
}
]
The array should be added in the JSON file without {}, and these curly brackets have to come inside the JSON array.
The code for
{
instances:[
{
"imagelist": "/oracle/public/oel6",
"label": "test_higgs",
"shape": "small",
"name" : "/Compute-computecli1/computeadmin/",
"networking" : {
"eth0" : {
"ipnetwork" : "/Compute-computecli1/computeadmin/ipnet"
}
}
}
]
}
is:
This code adds json array as a value to "instance" key, but I want to add json array without json key.
JsonObject ipnetwork = new JsonObject();
ipnetwork.addProperty("ipnetwork", ipNetworkName);
JsonObject interface_type = new JsonObject();
interface_type.add("eth0", ipnetwork);
JsonObject instance = new JsonObject();
instance.addProperty(imageListCmdText, "/oracle/public/oel6");
instance.addProperty("label","test_higgs");
instance.addProperty("shape","small");
instance.addProperty("name","/"+customerName);
instance.add("networking",interface_type);
JsonArray instances = new JsonArray();
instances.add(instance);
JsonObject launch_plan = new JsonObject();
launch_plan.add("instances", instances);
Please tell how does this code has to be changed in order to get the output asked above.
JsonObject launch_plan = new JsonObject();
launch_plan.add("instances", instances);
These two lines create the JSON object with curly braces. You don't need them, you can just remove them and use instances, which doesn't have curly braces as it's a json array and not a json object.
JsonObject ipnetwork = new JsonObject();
ipnetwork.addProperty("ipnetwork", ipNetworkName);
JsonObject interface_type = new JsonObject();
interface_type.add("eth0", ipnetwork);
JsonObject instance = new JsonObject();
instance.addProperty(imageListCmdText, "/oracle/public/oel6");
instance.addProperty("label","test_higgs");
instance.addProperty("shape","small");
instance.addProperty("name","/"+customerName);
instance.add("networking",interface_type);
JsonArray instances = new JsonArray();
instances.add(instance);
// not needed
//JsonObject launch_plan = new JsonObject();
//launch_plan.add("instances", instances);
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"]}