im been working apps with booking system, and i have problem with generate json and send it to server. the server catch this json
"buy":{
"583":[
{
"title":"Mr",
"nama_depan":"Mulia Rifai Aroyan",
"nama_belakang":"",
"tanggal_lahir":"0000-0-0",
"nationality":"Indonesia",
"identitas":"identitas",
"kelas_id":"254",
"kelas":"B",
"harga":"60000",
"seat":""
}
],
"584":[
{
"title":"Mr",
"nama_depan":"Mulia Rifai Aroyan",
"nama_belakang":"",
"tanggal_lahir":"0000-0-0",
"nationality":"Indonesia",
"identitas":"identitas",
"kelas_id":"254",
"kelas":"B",
"harga":"60000",
"seat":""
}
]
}
and i create generated json like this :
final JSONObject buy_child = new JSONObject();
final JSONArray buy = new JSONArray();
final JSONObject detail = new JSONObject();
for (int i=0;i<list_id_content.size();i++)
{
detail.put("title",gelar);
detail.put("nama_depan",nama_depan);
detail.put("nama_belakang",nama_belakang);
detail.put("tanggal_lahir",tanggal_lahir);
detail.put("nationality",nationality);
detail.put("identitas",identitas);
detail.put("kelas_id",id_event);
detail.put("kelas",kelas);
detail.put("harga",total_harga_pertiket);
detail.put("seat","");
buy.put(detail);
buy_child.put(id_event_content2,buy);
}
but its seems only generate json with same value (the last value)
how can i generate json like that and get all the value inside the loop?
thanks
edited : if i put JSONObject detail = new JSONObject(); inside the loop, it will give me this
Put the JSONObject detail = new JSONObject(); inside the for loop at the beginning.
Then put buy.put(detail); at the end of the loop (but inside).
You're only getting the last one right now because the buy.put is outside the for loop.
try with this
final JSONObject buy_child = new JSONObject();
final JSONArray buy;
for (int i=0;i<list_id_content.size();i++)
{
buy= new JSONArray();
final JSONObject detail = new JSONObject();
detail.put("title",gelar);
detail.put("nama_depan",nama_depan);
detail.put("nama_belakang",nama_belakang);
detail.put("tanggal_lahir",tanggal_lahir);
detail.put("nationality",nationality);
detail.put("identitas",identitas);
detail.put("kelas_id",id_event);
detail.put("kelas",kelas);
detail.put("harga",total_harga_pertiket);
detail.put("seat","");
buy.put(detail);
}
buy_child.put(id_event_content2,buy);
Related
I have following JSONObject (not array, which I don't mind to convert). I am trying to do two things:
get the count of genre entry as "poetry" (count = 2).
get the key value of author name and genre:
authorName = malcolm
genreName = newsarticle
authorName = keats
genreName = poetry
{ "AddressBook" :{
"Details" :{
"authorname" :{
"Author-malcolm":{
"genre" :"poetry"
}
"Author-keats":{
"genre" :"poetry"
}
}
}
}
}
Code which I tried:
public static void main(String[] args) throws Exception, IOException, ParseException {
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("My path to JSON"));
JSONObject jsonObject = (JSONObject) obj;
JSONArray arrayhere = new JSONArray();
arrayhere.add(obj);
System.out.println(arrayhere);
int count = 0;
for(int i = 0; i < arrayhere.size(); i++) {
JSONObject element = arrayhere.getJSONObject(i);//The method getJSONObject(int) is undefined for the type JSONArray
String branchName = element.getString("genre");//The method getString(String) is undefined for the type JSONObject
if(branchName.equals("poetry")) {
count ++;
}
}
System.out.println("Count f0r poetry genre=" + count);
}
}
I have looked at solutions all over. There is no question similar to this at stackoverflow. I am not sure if the procedure is correct.
A few problems here.
First, I'm not sure where you got that example JSON but you can't work with that. That's not even valid JSON Formatting.
Looks like you want something like this:
{
AddressBook:
[
{
authorname: "author-malcom",
genre:"poetry"
},
{
authorname: "author-keats",
genre: "poetry"
}
]
}
That's the structure you're trying to create in JSON.
So, you're parsing this in from a file into a JSONObject that has a key called AddressBook inside of it. That key points to an array of JSONObjects representing authors. Each of those objects will have a key called genre. You're trying to access the genre key and count on a condition.
What you did above was create attempt to create a JSONObject from an invalid string, and then add the entire JSONObject itself into the JSONArray. JSONArray.add() doesn't convert an object to an array, it literally adds it onto the array.
jsonObj => {"Name":"name1","Id":1000}
jsonArray.add(jsonObj)
jsonArray => [{"Name":"name1","Id":1000}]
That's what you did in your code above. You didn't create an array from a JSONObject, you added an object to the array.
Proper use is going to look like:
Object obj = parser.parse(new FileReader("path_to_file"));
JSONObject jobj = (JSONObject) obj;
//access key AddressBook
JSONArray author_array = jobj.getJSONArray("AddressBook");
int poetry = 0;
for(int i = 0; i < author_array.length(); i++) {
JSONObject author = (JSONObject) author_array.get(i);
if(author.getString("genre").equals("poetry")) {
poetry++;
}
}
To summarize, you're problems come from a lack of understanding about JSON Formatting and how to access elements within a JSON Object.
Paste in the sample JSONObject I gave you above here. That site will let you visualize what you're working with.
I'm trying to use JSON objects from the Guardian API.
This is the result from my call:
https://pastebin.com/wqggLEeZ
This is my code
JSONObject root = new JSONObject(jsonData);
JSONArray resultArray = root.getJSONObject("response").getJSONArray("results");
for(int i=0;i<resultArray.length();i++) {
JSONObject resultElement = resultArray.getJSONObject(i);
JSONObject blocksElement = resultElement.getJSONObject("blocks");
JSONObject mainElement = blocksElement.getJSONObject("main");
JSONArray elementsArray = mainElement.getJSONArray("elements");
JSONObject elementsElement = elementsArray.getJSONObject(0);
JSONArray assetsArray = elementsElement.getJSONArray("assets");
JSONObject assetsElement = assetsArray.getJSONObject(0);
String imageUrl = assetsElement.getString("file");
String articleTitle = resultElement.getString("webTitle");
news.add(new NewsList(articleTitle, imageUrl));
}
The code works fine except that it stops at 3 elements (i=2)
I tried replacing the imageUrl with "test" string in
news.add(new NewsList(articleTitle, imageUrl));
but it still stops at 3 elements.
But when I comment out the part where it finds the imageUrl the whole code works and gives me 10 results like it should do:
JSONObject root = new JSONObject(jsonData);
JSONArray resultArray = root.getJSONObject("response").getJSONArray("results");
for(int i=0;i<resultArray.length();i++){
JSONObject resultElement = resultArray.getJSONObject(i);
/*
JSONObject blocksElement = resultElement.getJSONObject("blocks");
JSONObject mainElement = blocksElement.getJSONObject("main");
JSONArray elementsArray = mainElement.getJSONArray("elements");
JSONObject elementsElement = elementsArray.getJSONObject(0);
JSONArray assetsArray = elementsElement.getJSONArray("assets");
JSONObject assetsElement = assetsArray.getJSONObject(0);
String imageUrl = assetsElement.getString("file");
*/
String articleTitle = resultElement.getString("webTitle");
news.add(new NewsList(articleTitle, "test"));
}
I've looked around in Android monitor and it seems like it has a problem that says
org.json.JSONException: No value for main
But that is not correct as the URL for the first 3 result is found without any problem, the problem only occurs after 3 iterations of the loop and I can't find any reason for why this is happening.
Use everywhere "opt" instead of "get', e.g.:
JSONObject assetsElement = assetsArray.optJSONObject(0);
String imageUrl = assetsElement.optString("file");
this is happening because of there is no field "main" in the response at some position in the line
JSONObject mainElement = blocksElement.getJSONObject("main");
so if at any of the position any of the fields are missing from the response, then after that position the code will not compile in JSON parsing.
sorry for bad english .
Hi i have a problem regarding the merge of JSONArray inside JSONObject. Below is what my JSONObject looks like:
{
"name":"sample.bin.png",
"coords":{
"1":{"x":[ 974, 975],"y":[154, 155},
"3":{"x":[124, 125],"y":[529]},
"8":{"x":[2048, 2049],"y":[548, 560, 561, 562, 563, 564 ]}
}
}
Now i have keys of those JSONObjects which i want to merge (inside coords).I wanted to merge x and y respectively into one JSONObject here is my code:
String[] tokens = request().body().asFormUrlEncoded().get("coords")[0].split(","); //here i recieve the String Array Keys of the coords i want to merge
if (!image.equals("")) {
JSONObject outputJSON = getImageJSON(image); //here comes the JSON which i posted above
JSONObject coordsPack = (JSONObject) outputJSON.get("coords");
JSONObject merged = new JSONObject();
merged.put("x", new JSONArray());
merged.put("y", new JSONArray());
for (String index : tokens) {
JSONObject coordXY = (JSONObject) coordsPack.get(index);
JSONArray xList = (JSONArray) coordXY.get("x");
JSONArray yList = (JSONArray) coordXY.get("y");
merged.get("x").addAll(xList);
merged.get("y").addAll(yList);
}
System.out.println(merged);
}
but problem is that i am having error at merged.get("x").addAll(xList); and merged.get("y").addAll(yList); i am unable to access the methods.
You must fill the lists first, and you should take out these following lines out of for loop.
merged.get("x").addAll(xList);
merged.get("y").addAll(yList);
BTW, it's apoor design to achieve your goal.
Don't you need to cast it into JSONArray class first, like you did for the 2 lines above?
As per suggestion of #cihan seven i am able to get the answer of my problem here is my solution:
JSONObject coordsPack = (JSONObject) outputJSON.get("coords");
JSONObject merged = new JSONObject();
JSONArray xList = new JSONArray();
JSONArray yList = new JSONArray();
for (String index : tokens) {
JSONObject coordXY = (JSONObject) coordsPack.get(index);
xList.addAll((JSONArray) coordXY.get("x"));
yList.addAll((JSONArray) coordXY.get("y"));
}
merged.put("x", xList);
merged.put("y", yList);
System.out.println(merged);
a json array is as given below
var data = [
{label:'gggg',data: [[(new Date('2011/12/01')).getTime(),53914],[(new Date('2012/1/02')).getTime(),32172],[(new Date('2012/2/03')).getTime(),824],[(new Date('2012/4/04')).getTime(),838],[(new Date('2012/6/05')).getTime(),755],[(new Date('2012/7/06')).getTime(),0],[(new Date('2012/8/07')).getTime(),0],[(new Date('2012/9/08')).getTime(),0],[(new Date('2012/10/09')).getTime(),0],[(new Date('2012/11/10')).getTime(),0],[(new Date('2012/12/11')).getTime(),0],[(new Date('2012/12/11')).getTime(),0]]}
];
in java class for creating the above similar json, i'm using the following code given below.
but the problem is there is a double quotes in each "(new Date(2012/12/01)).getTime()"
can anyone please tell me how to remove those double quotes
Query q1=session.createQuery("FROM VendorMonth");
List li1=q1.list();
String supname="",tempsupname;
JSONObject obj = new JSONObject();
JSONArray jsonarrmast = new JSONArray();
List s=new ArrayList();
JSONArray finals=new JSONArray();
JSONArray finalarray = new JSONArray();
for(int i=0;i<li1.size();i++)
{
HashMap hmap = new HashMap();
VendorMonth venmonth=(VendorMonth) li1.get(i);
tempsupname=venmonth.getId().getSupplierName();
if(i==0){
supname=venmonth.getId().getSupplierName();
}
if(!supname.equals(tempsupname)){
obj.put("label", supname);
obj.put("data", jsonarrmast);
jsonarrmast = new JSONArray();
s.add(obj);
finalarray.put(obj);
obj = new JSONObject();
supname=venmonth.getId().getSupplierName();
JSONArray jsonarr = new JSONArray();
String date=venmonth.getId().getYearnam()+"/"+venmonth.getId().getMonthnam()+"/01";
String ss=new String("(new Date("+date+")).getTime()");
jsonarr.put(ss);
jsonarr.put(venmonth.getId().getRentalrate());
jsonarrmast.put(jsonarr);
}
else
{
JSONArray jsonarr = new JSONArray();
String date=venmonth.getId().getYearnam()+"/"+venmonth.getId().getMonthnam()+"/01";
String ss=new String("(new Date("+date+")).getTime()");
jsonarr.put(ss);
jsonarr.put(venmonth.getId().getRentalrate());
jsonarrmast.put(jsonarr);
}
if(i==(li1.size()-1)){
obj.put("label", supname);
obj.put("data", jsonarrmast);
jsonarrmast = new JSONArray();
s.add(obj);
finalarray.put(obj);
}
}
but i'm getting the output as given below
[{"data":[["(new Date(2012/12/01)).getTime()",10976.23],["(new Date(2013/1/01)).getTime()",51213.8200000002],["(new Date(2013/2/01)).getTime()",32172.31],["(new Date(2013/3/01)).getTime()",824.600000000001],["(new Date(2013/4/01)).getTime()",838.000000000001],["(new Date(2013/5/01)).getTime()",755.780000000001],["(new Date(2013/6/01)).getTime()",50877.12]],"label":"Weather Ford"},{"data":[["(new Date(2012/12/01)).getTime()",24368.3],["(new Date(2013/1/01)).getTime()",1968.76]],"label":"Logan Tools"},{"data":[["(new Date(2012/12/01)).getTime()",3425.63],["(new Date(2013/1/01)).getTime()",731.75]],"label":"Pioneer tools"}]
You're not going to be able to create a JSON object that matches your declaration, because that's not a JSON object: it's Javascript code.
Once that Javascript code is ran, however, data will contain an object that can be serialized to JSON, and I'm assuming that's what you're trying to achieve.
What your Java code does is add a String to a BasicDBArray - the fact that it's interpreted as a String should not come as a surprise. By the same token, when you add an int or a boolean, they're added as ints and booleans, not strings.
What you actuall want to put in your BasicDBArray is the value that new Date('2011/12/01').getTime() would return if interpreted as Javascript: the number of milliseconds between 1970/01/01 and 2011/12/01. I'm assuming you can retrieve that through something like venmonth.getId().getDate().getTime(), or however it is you retrieve a Date instance from your venmonth object.
I have tried to run following code
Gson gson = new Gson();
String json = gson.toJson(result);
JSONObject jsonResponse = new JSONObject();
jsonResponse.put("sEcho", echo);
jsonResponse.put("iTotalRecords", iTotalRecords);
jsonResponse.put("iTotalDisplayRecords", iFilteredTotalRecords);
jsonResponse.put("aaData", json);
jsonResponse.toString();
JSONArray data = new JSONArray();
for (Object obj : result) {
JSONArray row = new JSONArray();
User user = (User) obj;
row.put(user.getId()).put(user.getUserName()).put(user.isEnabled());
data.put(row);
}
JSONObject jsonResponse2 = new JSONObject();
jsonResponse2.put("sEcho", echo);
jsonResponse2.put("iTotalRecords", iTotalRecords);
jsonResponse2.put("iTotalDisplayRecords", iFilteredTotalRecords);
jsonResponse2.put("aaData", data);
jsonResponse2.toString();
The result from toString function for both jsonResponse are as follows:
{"iTotalDisplayRecords":11,"iTotalRecords":11,"aaData":"[{\"creationTime\":0,\"enabled\":true,\"id\":1,\"loginDuration\":0,\"online\":false,\"password\":\"asda\",\"userName\":\"abiieez\"}]","sEcho":"1"}
{"iTotalDisplayRecords":11,"iTotalRecords":11,"aaData":[[1,"abiieez",true]],"sEcho":"1"}
I would like to eliminate the " symbol before [ and after ] from the first json response just like the second one (I noticed that the " is added after the array being put to the jsonResponse object). How can I accomplish this ?
Since you first convert your "result" to a String, and then add it to aaData, it will end up quoted, like a String should. If all you'd like to do is to remove the quotes, you could do something like this in line 2:
String json = "##" + gson.toJson(result) + "##";
and this in line 8:
jsonResponse.toString().replace("\"##", "").replace("##\"","");
(of course you need to choose the "quote marker" ## such that it will never appear as actual string content in your data anywhere else)
But the cleaner solution (although probably slower) would likely be to convert your String to an actual JSONObject by changing line 2 to:
JSONObject json = new JSONObject(gson.toJson(result));