double quotes found in json array - java

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.

Related

How to set array value in the jsonobject

I am getting the array values as
I need to construct the object as jsonObject.
So I have added like below but the returning object as an error.
How can I add the array as expected in the users.
Note: Here I am sending the users in array from a fragment to set the values in my payload
private String mUserArray; //value =["user1", "user2"]
mUserArray is added in the constructor.
final JsonArray array = new JsonArray();
array.add(mUserArray1);
final JsonObject jo = new JsonObject();
jo.addProperty("type", "value")
jo.add("usernames" , array); // If i set the userarray it failed to convert Added like this as well//new JsonPrimitive(mUserArray1)
return jo;
Expected Result:
{"type": "value", "usernames":["user1", "user2"]}
Actual Result:
{"type":"value","usernames":"[\"user1\", \"user2\"]"}
It seems like that you added the usernames property as a string literal rather than as a JSON array. You can construct a JsonArray of strings from a Java array the following way.
String[] userArray = {"user1", "user2"};
JsonArray userJsonArray = new JsonArray();
for(String user: userArray){
userJsonArray.add(new JsonPrimitive(user));
}
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("type", "value");
jsonObject.add("usernames", userJsonArray);
Note that JsonObject::addProperty only adds primitives to the JSON object rather than arrays or objects.

Android Java JsonObject put only last value

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);

Getting Json object inside a Json object in Java

So I have some code that is able to send this out:
{"id":1,
"method":"addWaypoint",
"jsonrpc":"2.0",
"params":[
{
"lon":2,
"name":"name",
"lat":1,
"ele":3
}
]
}
The server receives this JSON object as a string named "clientstring":
JSONObject obj = new JSONObject(clientstring); //Make string a JSONObject
String method = obj.getString("method"); //Pulls out the corresponding method
Now, I want to be able to get the "params" value of {"lon":2,"name":"name","lat":1,"ele":3} just like how I got the "method".
however both of these have given me exceptions:
String params = obj.getString("params");
and
JSONObject params = obj.getJSONObject("params");
I'm really at a loss how I can store and use {"lon":2,"name":"name","lat":1,"ele":3} without getting an exception, it's legal JSON yet it can't be stored as an JSONObject? I dont understand.
Any help is VERY appreciated, thanks!
params in your case is not a JSONObject, but it is a JSONArray.
So all you need to do is first fetch the JSONArray and then fetch the first element of that array as the JSONObject.
JSONObject obj = new JSONObject(clientstring);
JSONArray params = obj.getJsonArray("params");
JSONObject param1 = params.getJsonObject(0);
How try like that
JSONObject obj = new JSONObject(clientstring);
JSONArray paramsArr = obj.getJSONArray("params");
JSONObject param1 = paramsArr.getJSONObject(0);
//now get required values by key
System.out.println(param1.getInt("lon"));
System.out.println(param1.getString("name"));
System.out.println(param1.getInt("lat"));
System.out.println(param1.getInt("ele"));
Here "params" is not an object but an array. So you have to parse using:
JSONArray jsondata = obj.getJSONArray("params");
for (int j = 0; j < jsondata.length(); j++) {
JSONObject obj1 = jsondata.getJSONObject(j);
String longitude = obj1.getString("lon");
String name = obj1.getString("name");
String latitude = obj1.getString("lat");
String element = obj1.getString("ele");
}

simpleJson parsing in Java

I'm very new to parsing JSON. I have looked all over and cannot seem to grasp the idea to my particular problem. I'm having a hard time understanding how to get a JSON object from a JSON array. My example is below
[{"styleId":94,
"status":"verified",
"abv":"4.2",
"name":"Bud Light"}]
Here is my current code
JSONParser parser = new JSONParser();
Object obj = parser.parse(inputLine);
JSONObject jsonObject = (JSONObject) obj;
Long currPage = (Long)jsonObject.get("currentPage");
System.out.println(currPage);
JSONArray jArray = (JSONArray)jsonObject.get("data");
System.out.println(jArray);
inputLine is my orignal JSON. I have pulled a JSONArray out of the original JSONObject that has the "data" tag. Now this is where I'm stuck and given the JSONArray at the top. Not sure how to iterate through the Array to grab JUST the "name" tag.
Thanks for the help in advanced!
To iterate in a JSONArray you need to go through each element in a loop.
int resultSize = jArray.length();
JSONObject result;
for (int i = 0; i < resultSize; i++) {
result = resultsArray.getJSONObject(i);
String name = result.getString("name");
// do whatever you want to do now...
}
just use Gson . it works well out of the box with any object type you supply.
This is an example from the user's guide:
int[] ints2 = gson.fromJson("[1,2,3,4,5]", int[].class);

Is JSON same with GSON?

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));

Categories

Resources