create a json data object in java - 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);
}

Related

Converting JSONarray to ArrayList with Java

Hi i have simply problem, but i can find solution. If somebody can show to me solution.
...
(Unirest) HttpResponse<String> paluuREST = AbaXapi.HttpResponse(aString);
enter bring outside to me long Json Array:
So i put this inside Arraylist and short diffrent values...
"{\"body\":[{\"id\":\"1bc4aa42-1ef9-11e7-b023-97a5ff9c3a97\",\"name\":\"DFB-572\",\"imei\":13226005525791,\"vehicle_params\":{\"vin\":null,\"make\":null,\"model\":null,\"plate_number\":null}}]}"
Here is java code:
JSONObject jsonObject = new JSONObject(paluuREST);
System.out.println(jsonObject);
JSONArray jsonArray = jsonObject.getJSONArray("body");
ArrayList<Object> listdata = new ArrayList<Object>();
for (int i=0;i<jsonArray.length();i++){
//Adding each element of JSON array into ArrayList
listdata.add(jsonArray.get(i));
}
System.out.println("Each element of ArrayList");
for(int i=0; i<listdata.size(); i++) {
//Printing each element of ArrayList
System.out.println(listdata.get(i));
}
Error Message:
Exception in thread "main" org.json.JSONException: JSONObject["body"] is not a JSONArray.
at org.json.JSONObject.wrongValueFormatException(JSONObject.java:2628)
So how can be? How i need to change code, thanks for your help.
Please be more carefull in the formulation of the question, if everything is brought to the right, then there are no problems.
public static void main(String[] args) throws Exception {
String s = "{\"body\":[{\"id\":\"1bc4aa42-1ef9-11e7-b023-97a5ff9c3a97\",\"name\":\"DFB-572\",\"imei\":13226005525791,\"vehicle_params\":{\"vin\":null,\"make\":null,\"model\":null,\"plate_number\":null}}]}";
JSONObject obj = new JSONObject(s);
JSONArray body = obj.getJSONArray("body");
System.out.println(body);
ArrayList<Object> objects = new ArrayList<>();
for (Object o : body) {
objects.add(o);
}
System.out.println("objects = " + objects);
}
used org.json lib

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.

Creating JSONObjects in android

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.

Categories

Resources