I want to print from object like this :
{"data":[["Tiger Nixon","System
Architect","Edinburgh","5421","2011\/04\/25","$320,800"],["Garrett
Winters","Accountant","Tokyo","8422","2011\/07\/25","$170,750"]]}
i tried in java like this :
ArrayList<String> list = new ArrayList<String>();
list.add("Tiger Nixon");
list.add("System Architect");
list.add("Edinburgh");
list.add("2011\/04\/25");
list.add("$320,800");
JSONArray stateArray = JSONFactoryUtil.createJSONArray();
JSONObject stateObject;
stateObject = JSONFactoryUtil.createJSONObject();
stateObject.put("data", list); // i got an error in here
stateArray.put(stateObject);
System.out.println(stateArray);
But, i don't know how to implement object like that.
There's anyone can help me ?
Note :- Here JSONObject class whatever i used belongs to org.json.simple Jar Only. I used this class org.json.simple.JSONObject
What you have tried is. You are trying to create a JSONObject of Type ArrayList<String> which will not give you the expected Result, because your json array format is such like that
[["","",""],["","",""],["","",""],["","",""]] // arraylist inside an arraylist.
Your format like that a ArrayList inside an ArrayList but what you try is using only one ArrayList.
Here is your Code.
ArrayList<String> list = new ArrayList<String>(); //only one arrayList.
list.add("Tiger Nixon"); // adding values to the list.
list.add("System Architect");
list.add("Edinburgh");
list.add("2011\/04\/25");
list.add("$320,800");
Your Code will give output like this..
[{"data":"["","",""]"}, {"data":"["","",""]"}, {"data":"["","",""]"}]
Try this code instead of yours (below is just for sample use please try to manipulate this logic as per your need). this will give you the expected Result.
ArrayList<ArrayList<String>> final_arrObject = new ArrayList<ArrayList<String>();
ArrayList<String> list;
for(int i=0; i<5; i++){ //demo to add 5 ArrayList<String> to an ArrayList<ArrayList<String>>.
list = new ArrayList<String>(); //only one arrayList.
//at each iteration you may change you ArrayList Values.
list.add("Tiger Nixon"); // adding values to the list.
list.add("System Architect");
list.add("Edinburgh");
list.add("2011\/04\/25");
list.add("$320,800");
final_arrObject.add(list);
}
JSONObject obj_finalJSON= new JSONObject();
obj_finalJSON.put("data", final_arrObject);
System.out.println(obj_finalJSON.toString()); //it will print your json as a String.
You can achieve your objective like this:
JSONArray stateArray = JSONFactoryUtil.createJSONArray();
stateArray.put("Tiger Nixon");
stateArray.put("System Architect");
stateArray.put("Edinburgh");
stateArray.put("2011\/04\/25");
stateArray.put("$320,800");
JSONObject stateObject;
stateObject = JSONFactoryUtil.createJSONObject();
stateObject.put("data", stateArray);
System.out.println(stateObject.toString());
ArrayList <String> list = new ArrayList <String>();
list.add("Tiger Nixon");
list.add("System Architect");
JSONArray array = new JSONArray();
for (int i = 0; i < list.size(); i++) {
array.put(list.get(i));
}
JSONObject object = new JSONObject();
try {
obj.put("data", array);
} catch (JSONException e) {
e.printStackTrace();
}
There is a model,and some properties in it.
You can new some model info ,and add it to a List.
Then put this list to JSON,and print it json.toString().
If you want specific code, send message to me!
Related
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.
I wanna display a parsed json with my values . I mean , I wanna add some values to the json and display it . I can display all result from respond , but I wanna display just the json with my values not all data :)
here i have parsed allready my json
JSONObject jsonObject = new JSONObject(adresUrl);
JSONArray offerResources = jsonObject.getJSONArray("offerResources");
for(int y = 0; y < offerResources.length(); y++){
JSONObject currentTransfer = offerResources.getJSONObject(y);
JSONArray meetPoint = currentTransfer.getJSONArray("meetPoints");
for (int i = 0; i < meetPoint.length(); i++){
JSONObject currentMeetPoints = meetPoint.getJSONObject(i);
String startAddress = currentMeetPoints.getString("startAddress"); // here i wanna put some values , but i dont know how
// here is a litle piece of my json :)
"meetPoints": [
{
"startAddress": "....", // after the collon i have to put my value .
"startLocation": {
thank you for your help
I'm not sure if I understood your question fully but from what I got here is some solution. I simply created a string and couple of Json objects and jsonarray for adding the list of values and put it inside the main json object "jsonValueObject " and accumulate it inside meetPoints.
Accumulate(String key,Object Value) is a key value pair, meaning if key is created then Object is checked for being an array,and if this array has "values", it will be added else new array will be created. "Put" will replace the value if the key exists.
String jsonString = "{\"results\":[{\"Country\":\"value\",\"state\":\"value\" },
{ \"Country\":\"value\", \"state\":\"value\"}]}";
JSONObject meetPoints = new JSONObject(jsonDataString);
JSONObject jsonValueObject = new JSONObject();
JSONArray list = new JSONArray();
jsonValueObject.put("Country", "newValue");
jsonValueObject.put("state", "newValue");
jsonValueObject.put("city", "Chennai");
jsonValueObject.put("street", "Bharathiyar Street");
jsonValueObject.put("date", "14May2017");
jsonValueObject.put("time", "10:00AM");
list.put(jsonValueObject);
meetPoints.accumulate("values", list);
System.out.println(meetPoints);
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"}]
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.
Is there any way to convert a normal Java array or ArrayList to a Json Array in Android to pass the JSON object to a webservice?
If you want or need to work with a Java array then you can always use the java.util.Arrays utility classes' static asList() method to convert your array to a List.
Something along those lines should work.
String mStringArray[] = { "String1", "String2" };
JSONArray mJSONArray = new JSONArray(Arrays.asList(mStringArray));
Beware that code is written offhand so consider it pseudo-code.
ArrayList<String> list = new ArrayList<String>();
list.add("blah");
list.add("bleh");
JSONArray jsArray = new JSONArray(list);
This is only an example using a string arraylist
example key = "Name" value = "Xavier" and the value depends on number of array you pass in
try
{
JSONArray jArry=new JSONArray();
for (int i=0;i<3;i++)
{
JSONObject jObjd=new JSONObject();
jObjd.put("key", value);
jObjd.put("key", value);
jArry.put(jObjd);
}
Log.e("Test", jArry.toString());
}
catch(JSONException ex)
{
}
you need external library
json-lib-2.2.2-jdk15.jar
List mybeanList = new ArrayList();
mybeanList.add("S");
mybeanList.add("b");
JSONArray jsonA = JSONArray.fromObject(mybeanList);
System.out.println(jsonA);
Google Gson is the best library http://code.google.com/p/google-gson/
This is the correct syntax:
String arlist1 [] = { "value1`", "value2", "value3" };
JSONArray jsonArray1 = new JSONArray(arlist1);
For a simple java String Array you should try
String arr_str [] = { "value1`", "value2", "value3" };
JSONArray arr_strJson = new JSONArray(Arrays.asList(arr_str));
System.out.println(arr_strJson.toString());
If you have an Generic ArrayList of type String like ArrayList<String>. then you should try
ArrayList<String> obj_list = new ArrayList<>();
obj_list.add("value1");
obj_list.add("value2");
obj_list.add("value3");
JSONArray arr_strJson = new JSONArray(obj_list));
System.out.println(arr_strJson.toString());
My code to convert array to Json
Code
List<String>a = new ArrayList<String>();
a.add("so 1");
a.add("so 2");
a.add("so 3");
JSONArray jray = new JSONArray(a);
System.out.println(jray.toString());
output
["so 1","so 2","so 3"]
Convert ArrayList to JsonArray
: Like these [{"title":"value1"}, {"title":"value2"}]
Example below :
Model class having one param title and override toString method
class Model(
var title: String,
var id: Int = -1
){
override fun toString(): String {
return "{\"title\":\"$title\"}"
}
}
create List of model class and print toString
var list: ArrayList<Model>()
list.add("value1")
list.add("value2")
Log.d(TAG, list.toString())
and Here is your output
[{"title":"value1"}, {"title":"value2"}]