Creating JSONObjects in android - java

I need to form a JSON object like this.
{
"GroupID": 24536,
"Section": [1,2,3,4,5]
}
Here is what i have tried, but the section array is not getting properly formed when i look at my object structure.
JSONObject Object = new JSONObject();
Object.put("Group", GroupID);
int[] section = {1,2,3,4,5};
Object.put("Section", section);

Try:
JSONObject Object = new JSONObject();
Object.put("Group", GroupID);
Integer[] section = {1,2,3,4,5};
Object.put("Section", new JSONArray(Arrays.asList(section)));

Try:
JSONObject Object = new JSONObject();
Object.put("Group", GroupID);
int[] section = {1,2,3,4,5};
JSONArray arr = new JSONArray();
arr.put(section);
Object.put("Section", arr);
Or create a Collection and set it as the value:
Collection c = Arrays.asList(section);
Object.put("Section", c);

You need to make use of JSONArray for inserting set of values that represent an array, in this case int array.
String strJson = null;
try{
int[] section = {1,2,3,4,5};
JSONObject jo = new JSONObject();
jo.put("GroupId", 24536);
JSONArray ja = new JSONArray();
for(int i : section)
ja.put(i);
jo.put("Section", ja);
strJson = jo.toString();
}
catch (Exception e) {
e.printStackTrace();
}
Now you've got json string inside strJson.

Related

Java JSONObject getJsonArray Blank String

I have some JSON that is returned as follows:
[{"on_arrival_inst":"Ok","order_inst":"Ok","finished_inst":"Ok"},{"on_arrival_inst":"Arrive","order_inst":"Order","finished_inst":"Finished"}]
I am trying to split these into two arrays and get the strings out as follows:
jsonResultsObject = new JSONObject(result);
jsonArray = jsonResultsObject.getJSONArray("");
int count = 0;
String onArrive, onReady, onFinished;
while (count<jsonArray.length()){
JSONObject JO = jsonArray.getJSONObject(count);
onArrive = JO.getString("on_arrival_inst");
onReady = JO.getString("order_inst");
onFinished = JO.getString("finished_inst");
System.out.println(onArrive);
System.out.println(onReady);
System.out.println(onFinished);
count++;
}
However the code never goes into the loop, as the array is not getting populated from the JSONObject?
your result is JSONArray not JSONObject. That's why you must convert it to array not to object.
use
jsonResultsArray = new JSONArray(result);
instead of
jsonResultsObject = new JSONObject(result);
and the full code will be
jsonResultsArray = new JSONArray(result);
int count = 0;
String onArrive, onReady, onFinished;
while (count<jsonResultsArray.length()){
JSONObject JO = jsonResultsArray.getJSONObject(count);
onArrive = JO.getString("on_arrival_inst");
onReady = JO.getString("order_inst");
onFinished = JO.getString("finished_inst");
System.out.println(onArrive);
System.out.println(onReady);
System.out.println(onFinished);
count++;
}
#BigJimmyJones
The fact of that the code does not enter the loop is just because your JSONArray does not have a key named "" but it contains JSONObjects instead. Objects and arrays in JSON have different annotations. See: JSON Reference Website
So your code should be :
jsonResultsObject = new JSONObject(result);
String onArrive, onReady, onFinished;
for (int i=0;i<jsonArray.length();i++){
JSONObject JO = jsonArray.getJSONObject(i);
onArrive = JO.getString("on_arrival_inst");
onReady = JO.getString("order_inst");
onFinished = JO.getString("finished_inst");
System.out.println(onArrive);
System.out.println(onReady);
System.out.println(onFinished);
}
And also ensure that your code is inside a try - catch block to catch JSONException

create a json data object in java

Can someone provide me java code to create a json object as shown below
{"main":[
["one","two","three","four","five"],
["one","two","three","four","five"],
["one","two","three","four","five"],
["one","two","three","four","five"],
["one","two","three","four","five"]
]}
I have tried something like
Gson gson = new Gson();
JsonArray array = new JsonArray();
array.add(new JsonPrimitive("One"));
array.add(new JsonPrimitive("two"));
array.add(new JsonPrimitive("three"));
array.add(new JsonPrimitive("four"));
array.add(new JsonPrimitive("five"));
JsonObject jsonObject = new JsonObject();
jsonObject.add("main", array);
I am getting the result like below even when I am looping
{"main":["one","two","three","four","five"]}
like a single object. But I am expecting the result like
{"main":[
["one","two","three","four","five"],
["one","two","three","four","five"],
["one","two","three","four","five"],
["one","two","three","four","five"],
["one","two","three","four","five"]
]}
Many thanks in advance.
try this code to create json
Gson gson = new Gson();
JsonArray array = new JsonArray();
JsonArray child = new JsonArray();
child.add(new JsonPrimitive("One"));
child.add(new JsonPrimitive("two"));
child.add(new JsonPrimitive("three"));
child.add(new JsonPrimitive("four"));
child.add(new JsonPrimitive("five"));
for(int i=0;i<5;i++)
array.add(child);
JsonObject jsonObject = new JsonObject();
jsonObject.add("main", array);
System.out.println(jsonObject);
Assuming you're using Gson, this isn't the way it was designed to be used. Though this way is supported, it is not suggested, as you could use any json library to do this (SimpleJson).
Instead, Gson is able to directly serialize java objects we are familiar with, so you should represent your json object as a java object. JsonObject maps to a Map. JsonArray maps to List or an array. JsonPrimitives are mapped to their respective java primitive types (boolean, double, string, null)
// generate the object
Map<List<List<String>>> object = new HashMap<>();
List<List<String>> main = new ArrayList<>();
List<String> counts = Arrays.asList("one", "two", "three", "four", "five");
for (int i = 0; i < 5; i++) {
main.add(counts);
}
object.put("main", main);
// serialize it
String json = new Gson().toJson(object);
// deserializing it requires a typetoken or separate class representing the map object.
Map<List<List<String>>> desObj = new Gson().fromJson(json, new TypeToken<Map<List<List<String>>>>(){}.getType());
It appears "main" contains an array of arrays, so all you would have to do is add your array five times to another new array (e.g. call it mainArray) and then add mainArray to your jsonObject:
Create a new empty array: mainArray
Add array five times to mainArray
Add mainArray to jsonObject
You can try to convert the string representing your json data to JsonObject:
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class JsonQuestion {
public static void main(String[] args) {
String myJSON = "{\"main\":[\n"
+ " [\"one\",\"two\",\"three\",\"four\",\"five\"],\n"
+ " [\"one\",\"two\",\"three\",\"four\",\"five\"],\n"
+ " [\"one\",\"two\",\"three\",\"four\",\"five\"],\n"
+ " [\"one\",\"two\",\"three\",\"four\",\"five\"],\n"
+ " [\"one\",\"two\",\"three\",\"four\",\"five\"]\n"
+ "]}";
JsonParser jsonParser = new JsonParser();
JsonObject jsonObject = (JsonObject) jsonParser.parse(myJSON);
System.out.println("jsonObject: " + jsonObject.toString());
}
}
Gson gson = new Gson();
JsonArray array = new JsonArray();
array.add(new JsonPrimitive("One"));
array.add(new JsonPrimitive("two"));
array.add(new JsonPrimitive("three"));
array.add(new JsonPrimitive("four"));
array.add(new JsonPrimitive("five"));
JsonObject jsonObject = new JsonObject();
JsonArray marray = new JsonArray();
marray.add(array);
marray.add(array);
marray.add(array);
marray.add(array);
marray.add(array);
jsonObject.add("main", marray);
You can use below method to make json :
private void createJsonData(){
final String[] units = {"One","Two","Three","Four",
"Five"};
try {
JSONObject jsonObject = new JSONObject();
JSONArray jsonArray = new JSONArray();
JSONArray jsonArray1 = new JSONArray();
for (int j = 0; j < 5 ; j++) {
jsonArray1.put(units[j])
}
jsonArray.put(jsonArray);
jsonObject.put("main",jsonArray);
} catch (JSONException e) {
e.printStackTrace();
}
}
Use this method
public static void newjson() {
JSONObject json =new JSONObject();
List<List<String>> listoflist = new ArrayList<List<String>>();
List<String> list=new ArrayList<String>();
list.add("one");
list.add("one");
list.add("one");
listoflist.add(list);
listoflist.add(list);
try {
json.put("main",listoflist);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(json);
}

Appending JSON array to JSONObject

JSONObject jsonObj = new JSONObject("string");
jsonObj.toString();
"employees":[{"firstname":"stack","lastname":"overflow"}, {"firstname":"Happy","lastname":"Coding"}]
How can I append:
{"firstname":"Gloomy","lastname":"Sunday"}
to above json object
I want to get
"employees":[{"firstname":"stack","lastname":"overflow"}, {"firstname":"Happy","lastname":"Coding"}, {"firstname":"Gloomy","lastname":"Sunday"}]
upon jsonObj.toString();
Please do research this yourself first, this website is not here to do your computer science homework for you. Just cause I need some rep...
public class ex{
void example(){
try{
JSONObject jobj = new JSONObject("[{firstname:stack,lastname:overflow}]");
JSONObject jobj2 = new JSONObject("[{firstname:Happy,lastname:Coding}]");
JSONArray jarray = new JSONArray();
jarray.put(jobj);
jarray.put(jobj2);
}catch(JSONException e){
e.printStackTrace();
}
}
}
JSONObject jsonObj = new JSONObject();
JSONObject jo1 = new JSONObject("{"firstname":"Gloomy","lastname":"Sunday"}");
jsonObj.append("employees", jo1);

Converting string array into json

My String array has the following output each time it iterates through the loop
apple
orange
I want to convert my string array output to json format/jsonarray. I tried but it gives output as
{"fruits",apple}
{"fruits",orange}
I want my output as
{"fruits": [
{
"1": "apple"
}
{
"2": "orange"
}
I tried the below code
String[] strArray = new String[] {newString};
JSONObject json=new JSONObject();
//json.put("fruits", newString);
//System.out.println(json);
for(int i=0;i<strArray.length;i++)
{
System.out.print(strArray[i]+"\t");
json.put("",strArray[i]);
}
JSONObject obj = new JSONObject();
JSONArray array = new JSONArray();
for(int i=0;i<strArray.length;i++)
{
JSONObject fruit = new JSONObject();
fruit.put(""+i,strArray[i]);
array.put(fruit);
}
obj.put("Fruits",array);
System.Out.Println(obj.toString(2));
Try below code :-
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("key", "value");
String jsonString = jsonObject.toString();
I hope this will work for you.

Create JsonArray without key value

Please help me create jSonArray without keys. It should looks like:
"main" : ["one", "two", "three"]
I have tried it with empty key value:
private String generate(String value) {
Gson gson = new Gson();
JsonArray jsonArray = new JsonArray();
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("", value);
jsonArray.add(jsonObject);
return gson.toJson(jsonArray);
}
Result looks bad..
"main": "[
{\"\":\
"myString value\"}
]"
JsonObject obj = new JsonObject();
JsonArray array = new JsonArray();
array.add(new JsonPrimitive("one"));
array.add(new JsonPrimitive("two"));
array.add(new JsonPrimitive("three"));
obj.add("main", array);
You can do something like:
Gson gson = new Gson();
JsonArray array = new JsonArray();
array.add(new JsonPrimitive("one"));
array.add(new JsonPrimitive("two"));
array.add(new JsonPrimitive("three"));
JsonObject jsonObject = new JsonObject();
jsonObject.add("main", array);;
System.out.println(gson.toJson(jsonObject));
which outputs:
{"main":["one","two","three"]}
What you are trying to do is just to fill an array with primitive variables, to achieve that you have to change your code like this:
private String generate(String value) {
Gson gson = new Gson();
JsonArray jsonArray = new JsonArray();
jsonArray.add(new JsonPrimitive(value));
return gson.toJson(jsonArray);
}
Sample Code
JSONObject obj = new JSONObject();
JSONArray list = new JSONArray();
list.add("msg 1");
list.add("msg 2");
list.add("msg 3");
obj.put("", list);
You can use this to put an array without key.

Categories

Resources