I want to create a JSON string like this:
[{"addon_id":2,"addon_rate":1550},{"addon_id":3, "addon_rate":300}]
Is this possible? How?
My code as it stands:
String formattedString = BookingDetailsCartAdapter.addones_id.toString().replace("[", "").replace("]", "").trim();
String formattedString1 = BookingDetailsCartAdapter.addones_rate.toString().replace("[", "").replace("]", "").trim();
myjson="[{\"addon_id\":\""+formattedString+"\",\"addon_rate\":\""+formattedString1+"\"}]";
Your JSON means that it's an array which contains two objects with the keys addon_id and addon_rate. Both accept a number/integer as value. First you need to create a JSONArray which holds several JSONObjects. Then you have to create the JSONObjects which set your keys and values. After this you need to add those objects to your array. Your jsonArray contains the string above as soon as you print/toString() it
JSONArray jsonArray = new JSONArray();
JSONObject jsonObjOne = new JSONObject();
jsonObjOne.put("addon_id", 2);
jsonObjOne.put("addon_rate", 1550);
JSONObject jsonObjTwo = new JSONObject();
jsonObjTwo.put("addon_id", 3);
jsonObjTwo.put("addon_rate", 300);
jsonArray.put(jsonObjOne);
jsonArray.put(jsonObjTwo);
You can use GSON
Add in Gradle file
compile 'com.google.code.gson:gson:2.8.1'
public class Addon{
public int addon_id;
public int addon_rate;
}
Addon addon = new Addon ();
addon.addon_id=2;
addon.addon_id=1550;
Gson gson = new Gson();
String json = gson.toJson(addon); //
//--- For array
List<Addon > objList = new ArrayList<Addon >();
objList.add(new Addon (0, 1550));
objList.add(new Addon (1, 1552));
objList.add(new Addon (2, 1553));
String json = new Gson().toJson(objList);
System.out.println(json);
http://www.javacreed.com/simple-gson-example/
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 am trying to convert ArrayList of custom class to JsonArray. Below is my code. It executes fine but some JsonArray elements come as zeros even though they are numbers in the ArrayList. I have tried to print them out. Like customerOne age in the ArrayList is 35 but it is 0 in the JsonArray. What could be wrong?
ArrayList<Customer> customerList = CustomerDB.selectAll();
Gson gson = new Gson();
JsonElement element =
gson.toJsonTree(customerList , new TypeToken<List<Customer>>() {}.getType());
JsonArray jsonArray = element.getAsJsonArray();
Below code should work for your case.
List<Customer> customerList = CustomerDB.selectAll();
Gson gson = new Gson();
JsonElement element = gson.toJsonTree(customerList, new TypeToken<List<Customer>>() {}.getType());
if (! element.isJsonArray() ) {
// fail appropriately
throw new SomeException();
}
JsonArray jsonArray = element.getAsJsonArray();
Heck, use List interface to collect values before converting it JSON Tree.
As an additional answer, it can also be made shorter.
List<Customer> customerList = CustomerDB.selectAll();
JsonArray result = (JsonArray) new Gson().toJsonTree(customerList,
new TypeToken<List<Customer>>() {
}.getType());
Don't know how well this solution performs compared to the other answers but this is another way of doing it, which is quite clean and should be enough for most cases.
ArrayList<Customer> customerList = CustomerDB.selectAll();
Gson gson = new Gson();
String data = gson.toJson(customerList);
JsonArray jsonArray = new JsonParser().parse(data).getAsJsonArray();
Would love to hear from someone else though if, and then how, inefficient this actually is.
Consider a list of Objects of type Model.class
ArrayList<Model> listOfObjects = new ArrayList<Model>();
List to JSON
String jsonText = new Gson().toJson(listOfObjects);
JSON to LIST
Type listType = new TypeToken<List<Model>>() {}.getType();
List<Model> myModelList = new Gson().fromJson(jsonText , listType);
For Anyone who is doing it in Kotlin, you can get it this way,
val gsonHandler = Gson()
val element: JsonElement = gsonHandler.toJsonTree(yourListOfObjects, object : TypeToken<List<YourModelClass>>() {}.type)
List<> is a normal java object, and can be successfully transformed using standard gson object api.
List in gson looks like this:
"libraries": [
{
//Containing object
},
{
//Containing object
}
],
...
Use google gson jar, Please see sample code below,
public class Metric {
private int id;
...
setter for id
....
getter for id
}
Metric metric = new Metric();
metric.setId(1);
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.serializeNulls();
Gson gson = gsonBuilder.create();
System.out.println(gson.toJson(metric));
StringBuffer jsonBuffer = new StringBuffer("{ \"rows\": [");
List<Metric> metrices = new ArrayList<Metric>();
// assume you have more elements in above arraylist
boolean first = true;
for (Metric metric : metrices) {
if (first)
first = false;
else
jsonBuffer.append(",");
jsonBuffer.append(getJsonFromMetric(metric));
}
jsonBuffer.append("]}");
private String getJsonFromMetric(Metric metric) {
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.serializeNulls();
Gson gson = gsonBuilder.create();
return gson.toJson(metric);
}
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.
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);
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"}]