import net.sf.json.*;
public class JSONDemo {
/**
* #param args
*/
public static void main(String[] args) {
JSONObject mainObj = new JSONObject();
JSONObject jObj1 = new JSONObject();
JSONObject jObj2 = new JSONObject();
JSONArray jA1 = new JSONArray();
JSONArray jA2 = new JSONArray();
JSONArray mainArray= new JSONArray();
jObj1.accumulate("id", 17);
jObj1.accumulate("name", "Alex");
jObj1.accumulate("children", jA1);
mainArray.add(jObj1);
jObj2.accumulate("id", 94);
jObj2.accumulate("name", "Steve");
jObj2.accumulate("children", jA2);
//Adding the new object to jObj1 via jA1
jA1.add(jObj2);
mainObj.accumulate("ccgs", mainArray);
System.out.println(mainObj.toString());
}
}
The output I got is
{"ccgs":[{"id":17,"name":"Alex","children":[]}]}
I wanted the jObj2 within the children key of jObj1.
Apparently the node creation order has an impact on the generated string. If you change the object creation order, beginning with the children, the Json is correct.
See that code :
public static void main(String[] args) {
// first create the child node
JSONObject jObj2 = new JSONObject();
jObj2.accumulate("id", 94);
jObj2.accumulate("name", "Steve");
jObj2.accumulate("children", new JSONArray());
// then create the parent's children array
JSONArray jA1 = new JSONArray();
jA1.add(jObj2);
// then create the parent
JSONObject jObj1 = new JSONObject();
jObj1.accumulate("id", 17);
jObj1.accumulate("name", "Alex");
jObj1.accumulate("children", jA1);
// then create the main array
JSONArray mainArray = new JSONArray();
mainArray.add(jObj1);
// then create the main object
JSONObject mainObj = new JSONObject();
mainObj.accumulate("ccgs", mainArray);
System.out.println(mainObj);
}
The output is :
{"ccgs":[{"id":17,"name":"Alex","children":[{"id":94,"name":"Steve","children":[]}]}]}
If you wanted something like this {"ccgs":[{"id":17,"name":"Alex","children":{"id":94,"name":"Steve","children":[]}}]}
Then you can do like this.
JSONObject mainObj = new JSONObject();
JSONObject jObj1 = new JSONObject();
JSONObject jObj2 = new JSONObject();
JSONArray jA1 = new JSONArray();
JSONArray jA2 = new JSONArray();
JSONArray mainArray= new JSONArray();
jObj2.accumulate("id", 94);
jObj2.accumulate("name", "Steve");
jObj2.accumulate("children", jA2);
jObj1.accumulate("id", 17);
jObj1.accumulate("name", "Alex");
jObj1.accumulate("children", jObj2);
mainArray.add(jObj1);
//Adding the new object to jObj1 via jA1
jA1.add(jObj2);
mainObj.accumulate("ccgs", mainArray);
System.out.println(mainObj.toString());
Related
I have to post this type of data into Json. I don't want to convert cat in string. I only want single quote of item enclosing with double quote.
{"p02bvsd":"cal_dis","ovpsc7s":{"cat":["'Furniture'", "'Bikes'", "'Others'"]}}
My Json
JSONObject jsonobject1 = new JSONObject();
jsonobject.put("p02bvsd", "cal_dis");
jsonobject.put("ovpsc7s", jsonobject1);
jsonobject1.put("cat", hCategory);
Here hCategory is Hashset.
I want to json like this
{"p02bvsd":"cal_dis","ovpsc7s":{"cat": ["'Furniture'", "'Bikes'", "'Others'" ]}}
JSONObject jsonobject = new JSONObject();
jsonobject.put("p02bvsd", "cal_dis");
JSONObject jsonobject1 = new JSONObject();
List <String> list = new ArrayList <String>();
list.add("Furniture");
list.add("Bikes");
list.add("Others");
JSONArray array = new JSONArray();
for (int i = 0; i < list.size(); i++) {
array.put(list.get(i));
}
try {
jsonobject1.put("cat", array);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
jsonobject.put("ovpsc7s", jsonobject1);
String myString = "{\"p02bvsd\":\"cal_dis\",\"ovpsc7s\":{\"cat\":[\"\'Furniture\'\", \"\'Bikes\'\", \"\'Others\'\"]}}";
JSONObject wholeThing = new JSONObject(myString); // contains {"p02bvsd":"cal_dis","ovpsc7s":{"cat":["'Furniture'", "'Bikes'", "'Others'"]}}
JSONObject jsonp02bvsd = wholeThing.getJSONObject("p02bvsd"); // contains {"p02bvsd":"cal_dis"}
JSONObject jsonovpsc7s = wholeThing.getJSONObject("ovpsc7s"); // contains {"ovpsc7s":{"cat":["'Furniture'", "'Bikes'", "'Others'"]}
JSONArray jsonCatArray = jsonp02bvsd.getJSONArray("cat"); // contains ["'Furniture'", "'Bikes'", "'Others'"]
String first = jsonCatArray.getString(0); // contains 'Furniture'
I have this code where "Ocupacion" is object class that have another atribute objects. (since is a large class i don't post all the atributes of the class)
public String genHor(){
Collection<Ocupacion> ocupas = new ArrayList<>();
ocupas= H.makeOcupacion();
Gson gson = new Gson();
return gson.toJson(ocupas);
}
Then in another class where i recive the json String and i want to parse it. I do that:
public void assig(String json){
JsonObject obj = new JsonParser().parse(json).getAsJsonObject();
}
Then i get the java.lang.IllegalStateException: Not a JSON Object
String json is like that:
[{"sesionConcreta":{"grup":{"NumGr":10,"TamGr":200,"subgrupo":[{"NumSub":11,"TamSub":200}],"asignatura":"prop"},"sessio":{"HorasSes":2,"TipoSes":"TEORIA"}},"aula":{"NomAu":"a5105","Capacidad":200,"Tipo":"lab"},"diayHora":{"Dia":"L","Hora":8}}]
[{"sesionConcreta":{"grup":{"NumGr":10,"TamGr":200,"subgrupo":[{"NumSub":11,"TamSub":200}],"asignatura":"prop"},"sessio":{"HorasSes":2,"TipoSes":"TEORIA"}},"aula":{"NomAu":"a5105","Capacidad":200,"Tipo":"lab"},"diayHora":{"Dia":"L","Hora":8}}]
it is a json array not a json object because it is in [] not in {}:
JsonArray jsonArr = new JsonParser().parse(json).getAsJsonArray();
JsonObject obj = jsonArr.get(0).getAsJsonObject();
JsonObject sesionConcretaObj = obj.get("sesionConcreta").getAsJsonObject();
JsonObject groupObj = sesionConcretaObj.get("grup").getAsJsonObject();
int numGr = groupObj.get("NumGr").getAsInt();
The jsonString is actually a jsonArray not a jsonObject. Try with below:
String jsonStr = "[{\"sesionConcreta\":{\"grup\":{\"NumGr\":10,\"TamGr\":200,\"subgrupo\":[{\"NumSub\":11,\"TamSub\":200}],\"asignatura\":\"prop\"},\"sessio\":{\"HorasSes\":2,\"TipoSes\":\"TEORIA\"}},\"aula\":{\"NomAu\":\"a5105\",\"Capacidad\":200,\"Tipo\":\"lab\"},\"diayHora\":{\"Dia\":\"L\",\"Hora\":8}}]";
JSONArray jsonarray = new JSONArray(jsonStr);
for(int i = 0; i< jsonarray.length(); i++) {
JSONObject sesionConcreta = (JSONObject)jsonarray.getJSONObject(i).get("sesionConcreta");
JSONObject grup = (JSONObject)sesionConcreta.get("grup");
System.out.println(grup.get("NumGr"));
}
try this one:
public static void assig(String json){
Gson gson = new Gson();
Ocupacion[] occs = gson.fromJson(json, Ocupacion[].class);
System.out.println(occs);
}
I created a JSON file with JAVA.
Now I want to search a String in the JSON file.
JSONObject root = new JSONObject();
JSONObject courseObject1 = new JSONObject();
courseObject1.put("name", "MEA");
courseObject1.put("author", "Mn");
root.put("object", courseObject1);
//------------------------------------
JSONObject courseObject2 = new JSONObject();
courseObject2.put("name", "MES");
courseObject2.put("author", "Ma");
root.put("object2", courseObject2);
I want to know in which courseObject is "MES".
(Maby in the finish programm are more courseObjects)
You can proceed as follows:
for(int i = 0; i < root.length(); i++) {
JSONObject obj = root.getJSONObject(i);
if(obj.getString("name").equals("MES")) {
// Do something with the course
}
}
I want to create a object array in JSONObjet. But not run in java. Please help me.
JSONObject jo[] = new JSONObject[10];
jo[0].put("A","a");
jo[1].put("B","b");
jo[2].put("B","c");
...
java
You are probably looking for this -
JSONObject jo[] = new JSONObject[10];
jo[0]=new JSONObject().put("A","a");
jo[1]=new JSONObject().put("B","b");
jo[2]=new JSONObject().put("B","c");
Use JSONArray instead of that like this -
public void getJSONArray() throws JSONException {
JSONArray jo= new JSONArray();
JSONObject obj1= new JSONObject();
obj1.put("A","a");
JSONObject obj2= new JSONObject();
obj2.put("B","b");
JSONObject obj3= new JSONObject();
obj3.put("B","c");
jo.put(obj1);
jo.put(obj2);
jo.put(obj3);
System.out.println(jo.toString());
}
Output -
[{"A":"a"},{"B":"b"},{"B":"c"}]
I have a List<class> that I would like to convert into a json object and then traverse the data out of the json object.
If this were just a List<String> I could just do something like:
JSONObject obj = new JSONObject();
List<String> sList = new ArrayList<String>();
sList.add("val1");
sList.add("val2");
obj.put("list", sList);
Then I could traverse the list like:
JSONArray jArray = obj.getJSONArray("list");
for (int ii = 0; ii < jArray.size(); ii++)
System.out.println(jArray.getString(ii));
The problem with using the class is that I need to have access to data within each class element of my List<class> and I don't know how to encode that / traverse it into JSON. Any help would be greatly appreciated.
Call getJSONObject() instead of getString(). That will give you a handle on the JSON object in the array and then you can get the property off of the object from there.
For example, to get the property "value" from a List<SomeClass> where SomeClass has a String getValue() and setValue(String value):
JSONObject obj = new JSONObject();
List<SomeClass> sList = new ArrayList<SomeClass>();
SomeClass obj1 = new SomeClass();
obj1.setValue("val1");
sList.add(obj1);
SomeClass obj2 = new SomeClass();
obj2.setValue("val2");
sList.add(obj2);
obj.put("list", sList);
JSONArray jArray = obj.getJSONArray("list");
for(int ii=0; ii < jArray.length(); ii++)
System.out.println(jArray.getJSONObject(ii).getString("value"));
Let us assume that the class is Data with two objects name and dob which are both strings.
Initially, check if the list is empty. Then, add the objects from the list to a JSONArray
JSONArray allDataArray = new JSONArray();
List<Data> sList = new ArrayList<Data>();
//if List not empty
if (!sList.isEmpty()) {
//Loop index size()
for(int index = 0; index < sList.size(); index++) {
JSONObject eachData = new JSONObject();
try {
eachData.put("name", sList.get(index).getName());
eachData.put("dob", sList.get(index).getDob());
} catch (JSONException e) {
e.printStackTrace();
}
allDataArray.put(eachData);
}
} else {
//Do something when sList is empty
}
Finally, add the JSONArray to a JSONObject.
JSONObject root = new JSONObject();
try {
root.put("data", allDataArray);
} catch (JSONException e) {
e.printStackTrace();
}
You can further get this data as a String too.
String jsonString = root.toString();
This is how I do it using Google Gson. I am not sure, if there are a simpler way to do this (with or without an external library).
Type collectionType = new TypeToken<List<Class>>() {
}.getType();
String gsonString = new Gson().toJson(objList, collectionType);
You could use a JSON serializer/deserializer like flexjson to do the conversion for you.
Just to update this thread, here is how to add a list (as a json array) into JSONObject.
Plz substitute YourClass with your class name;
List<YourClass> list = new ArrayList<>();
JSONObject jsonObject = new JSONObject();
org.codehaus.jackson.map.ObjectMapper objectMapper = new
org.codehaus.jackson.map.ObjectMapper();
org.codehaus.jackson.JsonNode listNode = objectMapper.valueToTree(list);
org.json.JSONArray request = new org.json.JSONArray(listNode.toString());
jsonObject.put("list", request);