How to set array value in the jsonobject - java

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.

Related

Android - JSON - How do I create a JSON Object & JSON Array to match this format using JSONObject & JSONArray Types?

How do I create a JSON Object & JSON Array to match this format using JSONObject & JSONArray Types?
{"PeripheralList":
[{"Category":"BP","CollectionTime":"2015-12-28T09:09:22-05:00",
"DeviceInfo":null,
"Readings":[
[{"Name":"SYS","Type":"INT","Value":"200"},
{"Name":"DIA","Type":"INT","Value":"199"},
{"Name":"HTR","Type":"INT","Value":"102"},
{"Name":"READINGTIME","Type":"DATETIME","Value":"2015-12-27T08:12:53-05:00"}]
]},
{"Category":"HR","CollectionTime":"2015-12-28T09:09:22-05:00",
"DeviceInfo":[{"Name":"UNITS","Value":"Rate"}],
"Readings":[
[{"Name":"HR","Type":"DECIMAL","Value":"200.7"},
{"Name":"READINGTIME","Type":"DATETIME","Value":"2015-12-27T07:26:49-05:00"}],
[{"Name":"HR","Type":"DECIMAL","Value":"155.2"},
{"Name":"READINGTIME","Type":"DATETIME","Value":"2015-12-27T14:39:11-05:00"}]
]}
]}
Any help would be appreciated. Thanks.
You should be able to pass the JSON string directly to the constructor.
JSONObject mainObject = new JSONObject(jsonString);
Below should give you an idea of how it works when you want to manually create a JSON Object.
JSONObject mainObject = new JSONObject(); // Main Object.
JSONArray categoryArray; // Category Array.
JSONObject categoryObject; // Category Object.
JSONArray readingsMainArray; // An array of arrays.
JSONArray readingsChildArray; // A child array.
JSONObject readingsObject; // A readings entry.
// Create arrays.
readingsMainArray = new JSONArray();
readingsChildArray = new JSONArray();
// Create JSONObject.
readingsObject = new JSONObject();
// Put values.
readingsObject.put("Name":"SYS");
readingsObject.put("Type":"INT");
readingsObject.put("Value":"200");
// Add to the child array.
readingsChildArray.put(readingsObject);
// Repeat 3 times for the other values.
// Now add the readings child array to the main array.
readingsMainArray.put(readingsChildArray);
// Now the category JSONObject.
categoryObject = new JSONObject();
// Put values.
categoryObject.put("Category","BP);
categoryObject.put("CollectionTime","2015-12-28T09:09:22-05:00");
categoryObject.put("DeviceInfo",null);
categoryObject.put("Readings", readingsMainArray);
// Put the category object into the category array.
categoryArray = new JSONArray();
categoryArray.put(categoryObject);
// Repeat this process for the "second" category array.
// Add category array to the main object.
mainObject.put("PeripheralList",categoryArray);
Let me know if this helps.

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

Put a Java Map to JSON

I have a map of string objects and keys that I wish to put to a json file. I have read that the way to do it is by converting it to an array, and it only works with maps where both the object and key are strings. I can create a JSONObject from the map fine, but cannot put that to an array. Can someone tell me why this does not work?
private static final String JSON_USER_VOTES = "user_votes";
private Map<String, String> mCheckedPostsMap; //This is populated elsewhere
JSONObject obj=new JSONObject(mCheckedPostsMap);
JSONArray array=new JSONArray(obj.toString()); // <<< Error is on this line
json.put(JSON_USER_VOTES, array);
Here is the error:
org.json.JSONException: Value {"232":"true","294":"true"} of type org.json.JSONObject cannot be converted to JSONArray
If you want all of initial map entries enclosed in one JSON object, you can use:
JSONArray array = new JSONArray().put(obj);
This will produce something like
[{"key1:"value1","key2":"value2"}]
If you want each of initial map entries as different JSON object, you can use:
JSONObject obj = new JSONObject(map);
JSONArray array = new JSONArray();
for(Iterator iter = obj.keys(); iter.hasNext(); ){
String key = (String)iter.next();
JSONObject o = new JSONObject().put(key, map.get(key));
array.put(o);
}
This will produce something like
[{"key1:"value1"}, {"key2":"value2"}]

double quotes found in json array

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.

Create a JSONArray

How can I create a JSONArray, since creating a JSONObject is quite simple:
JSONObject j = new JSONObject();
j.put("key",value);
Right now I can put another string in the JSONObject, or a string representation of a JSONObject.
But how can I create a JSONArray and insert it to the JSONObject?
But how can I create a JSONArray and insert it to the JSONObject?
You can create JSONArray same like you have tried to create JSONObject.
Creating time:
For example:
JSONArray myArray = new JSONArray();
JSONObject j = new JSONObject();
j.put("key",value);
j.put("array",myArray);
Retrieving time:
you can fetch the value of String or JSONObject or any by their key name. For example:
JSONArray myArray = objJson.getJSONArray("array");
You can do it like:
String[] data = {"stringone", "stringtwo"};
JSONArray json = new JSONArray(Arrays.toString(data));
Or, create a JSONArray object and use the put method(s) to add any Strings you want. To output the result, just use the toString() method.
Why dont you use Gson library its very easy to convert any object into json array, json object
Download Gson library then use like
Gson gson=new Gson();
String json=gson.toJson(object);
if Object is of List object it will create json array
Gson gson = new Gson();
reverse parsing for array --
listObject = gson.fromJson(json,
new TypeToken<List<ClassName>>() {
}.getType());
for single object
object = gson.fromJson(json, ClassName.class);

Categories

Resources