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"}]
Related
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'm using jackson lib to add json object into jsonarray then Stringify my jsonarray to save it into my a table as string
JsonObject obj = new JsonObject();
obj.put("id",1).put("data","test");
JsonArray arr = new JsonArray();
arr.add(obj);
arr.toString();
//out : [{"map":{"id":1,"data":"test"},"empty":false}]
//result wanted : [{"id":1,"data":"test"}]
So how can I get the last result without map and empty keys, and why it adds those keys in the first place ?
I made small changes to the code, i used the following maven dependency https://mvnrepository.com/artifact/org.json/json/20160810 and you are using org.json but not jackson.
JSONObject obj = new JSONObject();
try {
obj.put("id",1).put("data","test");
} catch (JSONException e1) {
e1.printStackTrace();
}
JSONArray arr = new JSONArray();
arr.put(obj);
System.out.println(arr.toString());
output: [{"data":"test","id":1}]
ok, finally I get it. So, the documentation for the jackson module clearly shows how serialization of a JsonObject should be done. It is not using toString():
Serialization (JsonElement -> String)
ObjectMapper mapper = new ObjectMapper();
om.registerModule(new VertxJsonModule());
String jsonObject = mapper.writeValueAsString(new JsonObject());
String jsonArray = mapper.writeValueAsString(new JsonArray());
I get the following JSON:
[
{
"user_id": "someValue"
}
]
It's saved inside a String.
I would like to convert it to a JSONObject which fails (as the constructor assumes a JSON to start with {). As this doesn't seem to be possible I'd like to convert it to a JSONArray. How can I do that with SimpleJson?
JSONParser parser = new JSONParser();
JSONArray array = (JSONArray)parser.parse("[{\"user_id\": 1}]");
System.out.println(((JSONObject)array.get(0)).get("user_id"));
You need to cast to a JSONArray as that is what the string contains.
For your task you could use code as bellow:
String t = "[{\"user_id\": \"someValue\"}]";
JSONParser parser = new JSONParser();
JSONArray obj = (JSONArray) parser.parse(t);
System.out.println(obj.get(0));
And result would be JSONObject.
String actualJsonObject = // assuming that this variable contains actual object what ever u want to pass as per your question says
JSONParser parser = new JSONParser();
JSONArray userdataArray= (JSONArray) parser.parse(actualJsonObject );
if(userdataArray.size()>0){
for (Object user : userdataArray) {
JSONObject jsonrow=(JSONObject)parser.parse(String.valueOf(user));
String User_Id= (String)jsonrow.get("user_Id"); \\ Each User_Id will be displayed.
} else{
System.out.println("Empty Array....");
}
It works for me.
String jsonString = "[{\"user_id\": \"someValue\"}]";
JSONArray jsonArray = new JSONArray();
JSONParser parser = new JSONParser();
try {
jsonArray = (JSONArray) parser.parse(js);
} catch (ParseException e) {
e.printStackTrace();
}
I'm trying to parse below json file:
{"units":[{"id":42,
"title":"Hello World",
"position":1,
"v_id":9,
"sites":[[{"id":316,
"article":42,
"clip":133904
}],
{"length":5}]
}, ..]}
This is what I have tried:
Object obj = null;
JSONParser parser = new JSONParser();
Object unitsObj = parser.parse(new FileReader("file.json");
JSONObject unitsJson = (JSONObject) unitsObj;
JSONArray units = (JSONArray) unitsJson.get("units");
Iterator<String> unitsIterator = units.iterator();
while(unitsIterator.hasNext()){
Object uJson = unitsIterator.next();
JSONObject uj = (JSONObject) uJson;
obj = parser.parse(uj.get("sites").toString());
JSONArray jsonSites = (JSONArray) obj;
for(int i=0;i<jsonSites.size();i++){
JSONObject site = (JSONObject)jsonSites.get(i); // Exception happens here.
System.out.println(site.get("article");
}
}
The code is not working when I try to parse the inner json array, so I get:
Exception in thread "main" java.lang.ClassCastException: org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject
The exception is pointing to this line:
JSONObject site = (JSONObject)jsonSites.get(i);
Any help? tnx.
I've found a working code:
JSONParser parser = new JSONParser();
Object obj = parser.parse(content);
JSONArray array = new JSONArray();
array.add(obj);
If you don't need the array (like the author), you can simply use
JSONParser parser = new JSONParser();
Object obj = parser.parse(content);
The first element of the sites array is an array, as you can see indenting the JSON:
{"units":[{"id":42,
...
"sites":
[
[
{
"id":316,
"article":42,
"clip":133904
}
],
{"length":5}
]
...
}
Therefore you need to treat its value accordingly; probably you could do something like:
JSONObject site = (JSONObject)(((JSONArray)jsonSites.get(i)).get(0));
this worked:
System.out.println("resultList.toString() " + resultList);
org.json.JSONObject obj = new JSONObject(resultList);
org.json.JSONArray jsonArray = obj.getJSONArray(someField);
for(int i=0;i<jsonArray.length();i++){
System.out.println("array is " + jsonArray.get(i));
}
JSONObject site=jsonSites.getJSONObject(i) should work out
JSONObject obj=(JSONObject)JSONValue.parse(content);
JSONArray arr=(JSONArray)obj.get("units");
System.out.println(arr.get(1)); //this will print {"id":42,...sities ..}
#cyberz is right but explain it reverse
You can first read the whole content of file into a String.
FileInputStream fileInputStream = null;
String data="";
StringBuffer stringBuffer = new StringBuffer("");
try{
fileInputStream=new FileInputStream(filename);
int i;
while((i=fileInputStream.read())!=-1)
{
stringBuffer.append((char)i);
}
data = stringBuffer.toString();
}
catch(Exception e){
LoggerUtil.printStackTrace(e);
}
finally{
if(fileInputStream!=null){
fileInputStream.close();
}
}
Now You will have the whole content into String ( data variable ).
JSONParser parser = new JSONParser();
org.json.simple.JSONArray jsonArray= (org.json.simple.JSONArray) parser.parse(data);
After that you can use jsonArray as you want.
If you want to re-filter the json data you can use following method. Given example is getting all document data from couchdb.
{
Gson gson = new Gson();
String resultJson = restTemplate.getForObject(url+"_all_docs?include_docs=true", String.class);
JSONObject object = (JSONObject) new JSONParser().parse(resultJson);
JSONArray rowdata = (JSONArray) object.get("rows");
List<Object>list=new ArrayList<Object>();
for(int i=0;i<rowdata.size();i++) {
JSONObject index = (JSONObject) rowdata.get(i);
JSONObject data = (JSONObject) index.get("doc");
list.add(data);
}
// convert your list to json
String devicelist = gson.toJson(list);
return devicelist;
}
JSONObject site = (JSONObject)jsonSites.get(i); // Exception happens here.
The return type of jsonSites.get(i) is JSONArray not JSONObject.
Because sites have two '[', two means there are two arrays here.
use your jsonsimpleobject direclty like below
JSONObject unitsObj = parser.parse(new FileReader("file.json");
JSONObject baseReq
LinkedHashMap insert = (LinkedHashMap) baseReq.get("insert");
LinkedHashMap delete = (LinkedHashMap) baseReq.get("delete");
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());