Convert Arraylist of HashMaps to Json String (GSON) - android

I have created 3 HashMaps all stored into an Arraylist but I cannot make it into a JSON String, I am using the GSON library.
Any help would kindly be appreciated.
Below you can see all the 3 hashmaps and the ArrayList x am adding them to.
private void createAdditionalPackages() {
if (chemoBtn.isChecked()) {
chemo.put("name", "chemo");
chemo.put("price", chemoButtonPrice);
}
if (cremBtn.isChecked()) {
cremation.put("name", "crematie");
cremation.put("price", cremationButtonPrice);
}
if (travenBtn.isChecked()) {
travel.put("name", "reisverz");
travel.put("price", travelButtonPrice);
}
x.add(chemo);
x.add(cremation);
x.add(travel);
List<JsonObject> jsonObjectList = new ArrayList<>() ;
for(HashMap<String, String> data : x){
JsonObject object = new JsonObject(data);
jsonObjectList.add(object);
}
JsonArray additional_coverages = new JsonArray(jsonObjectList);
See error :

JsonArray additional_coverages = new JsonArray();
// Iterate over your Hashmap
for (Map.Entry<String,String> data : x.entrySet()) {
// Create your JsonObject and use addProperty
JsonObject object = new JsonObject();
object.addProperty(data.getKey(), data.getValue());
// Add data in your JsonArray
additional_coverages.add(object);
}

You cannot directly add list of JsonObject to JsonArray
you can use something like this.
JsonArray additional_coverages = new JsonArray();
for(singleItem in jsonObjectList){
additional_coverages.put(singleItem )
}

Related

How to post data in my json format

I am new in android and confuse in post data in json format using volley lib.
My Json param like:
{
key
comKey
addLeadArray
[{
key
autoid
images[image1,image2...]
audio
}
{
key
autoid
images[image1,image2...]
audio
}
{
key
autoid
images[image1,image2...]
audio
}.....]
}
I am trying code:
JSONObject object = new JSONObject();
object.put("key", "1");
object.put("comKey", "2");
................
JSONObject addLeadArrayObj= new JSONObject();
AddLeadArray.put("key", "1");
AddLeadArray.put("autoid", "34");
................
object.put("addLeadArray", addLeadArrayObj);
But its create {{}} and I want to make json object for above json formate. what can I do please help me and pls give code snippt.
What you are doing is creating JSONObject AddLeadArray and putting it in the main JsonObject.
AddLeadArray is an array, so make it an object of JSONArray instead of JSONObject.
JSONObject object = new JSONObject();
object.put("key", "1");
object.put("comKey", "2");
................
// Create JSONArray
JSONArray addLeadArrayObj= new JSONArray();
// Create JSONObject for jsonArray
JSONObject object2 = new JSONObject();
object2.put("key", "1");
object2.put("autoid", "34");
// put object2 in addLeadArray
addLeadArrayObj.put(object2);
// put addLeadArray in main jsonobject
object.put("addLeadArray", addLeadArrayObj);
Refer more here: Add JsonArray to JsonObject
How about using Gson.
Gson gson = new Gson(); // Or use new GsonBuilder().create();
MyType target = new MyType();
String json = gson.toJson(target); // serializes target to Json
MyType target2 = gson.fromJson(json, MyType.class); // deserializes json into target2
If the object that your are serializing/deserializing is a ParameterizedType (i.e. contains at least one type parameter and may be an array) then you must use the toJson(Object, Type) or fromJson(String, Type) method.
Here is an example for serializing and deserialing a ParameterizedType:
Type listType = new TypeToken<List<String>>() {}.getType();
List<String> target = new LinkedList<String>();
target.add("blah");
Gson gson = new Gson();
String json = gson.toJson(target, listType);
List<String> target2 = gson.fromJson(json, listType);
Here is the Gson Help.

How to pass bulk of json objects into Json array

Hi can any one help for this issue, i am not able to pass arraylist of values in bellow json array.
please help me.
Ex values:
Arraylist<String> list_values = new Arraylist<String>();
list_values.add(111);
list_values.add(222);
list_values.add(333);
Arraylist<String> list_labeltext = new Arraylist<String>();
list_labeltext.add("Mileage Entry");
list_labeltext.add("Tip Amount");
list_labeltext.add("Travel Time");
Arraylist<String> list_optionId = new Arraylist<String>();
list_optionId.add("1");
list_optionId.add("2");
list_optionId.add("3");
i want pass above array list values in json array like this:
ClockOUTEmployeeReponse":[{"Response":[{"Response":[{"Value":"111"}],"LabelText":"Mileage Entry","ClockOUTOptionId":2},{"Response":[{"Value":"222"}],"LabelText":"Tip Amount","ClockOUTOptionId":4},{"Response":[{"Value":"333"}],"LabelText":"Travel Time","ClockOUTOptionId":3}]
My Code is as follows:
JSONObject parentData = new JSONObject();
JSONArray req_parameters = new JSONArray();
JSONObject req_clockout_obj = new JSONObject();
JSONArray req_arr = new JSONArray();
JSONObject value = new JSONObject();
req_clockout_obj.put("ClockOUTOptionId", 1);
req_clockout_obj.put("LabelText", labelText);
for (int i = 0; i < list_values.size; i++) {
if (i == 0) {
value.put("Value", list_values.get(0));
req_arr.put(value);
req_clockout_obj.put("Response", req_arr);
} else if (i == 1) {
value.put("Value", list_values.get(1));
req_arr.put(value);
req_clockout_obj.put("Response", req_arr);
} else if (i == 2) {
value.put("Value", list_values.get(2));
req_arr.put(value);
req_clockout_obj.put("Response", req_arr);
}
}
req_parameters.put(req_clockout_obj);
parentData.put("ClockOUTEmployeeReponse", req_parameters);
Best way to implement this is using a Model Class and fetch data in a instance of that Model(POJO) then convert that into json string.
For this You need GSON library.
Steps :
1. Make a POJO(Model Class) of according to you json format.
2. Then fetch data in a object of that POJO.
3. Then U can convert that POJO's object into json using
DataObject obj = new DataObject();
Gson gson = new Gson();
// convert java object to JSON format,
// and returned as JSON formatted string
String json = gson.toJson(obj);
Please follow the following link :
http://www.mkyong.com/java/how-do-convert-java-object-to-from-json-format-gson-api/
Please use this, If you need any help then let me know.

Convert JSONObject into String array

I'm receiving a JSONObject like this
{"tag":"value1", "tag":"value2", .............}
How do I make it into a String array of
["value1", "value2"]
Create the Arraylist and get the string from the jsonobject and stored it in the arraylist.
Do like this
ArrayList tagarray=new ArrayList();
JSONObject jo=new JSONObject(jsonstring);
for(int i=0;i<jo.length();i++){
tagarray.add(jo.getString("tag"));
}
Try this way
JSONObject obj = new JSONObject("");
Iterator<String> itr = obj.keys();
int i=0;
String[] values = new String[obj.length()];
while(itr.hasNext()){
values[i++] = obj.getString((String)itr.next());
}
Use following code.
ArrayList array=new ArrayList();
JSONObject jo=new JSONObject(jsonstring);
for(int i=0;i<jo.length();i++){
array.add(jo.getString("tag"));
}
String[] Arr = new String[array.size()];
Arr = array.toArray(Arr);
Or you have another option.
JSONObject jo=new JSONObject(jsonstring);
String[] array = new String[jo.length()];
for(int i=0;i<jo.length();i++){
array[i] = jo.getString("tag");
}
There is super cool , lib called GSON , which is really helpfull for converting all type of JSON into its object .
If tags are going to be tag1, tag2 and so on...you can use a for loop,
string[i] = jsonObj.getString("tag"+i);
Or you can make a model class with datatype of String or ArrayList tag , eg.
class ModelClass{
ArrayList<String> tag;
//getter setter here
}
And with that use Gson for JSON parsing and mapping the data,
Gson gson = new Gson();
modelClass= gson.fromJson(yourJson,ModelClass.class);
And your work is done. You have each value in the ArrayList tag.
This is more useful for parsing and mapping long and-or complex json strings.
https://code.google.com/p/google-gson/
For Naming discrepancies(according to the variables in webservice), can use annotations like #SerializedName. (So no need to use Serializable)

create an array of all the keys in a JSONObject Android

Hi im wanting to create an array of all the keys in a JSONObject. my understanding (please correct me if i'm wrong) is that i need to convert the JSONObject to a Map and then create an Array from this does anyone know how to do this?
No need to convert JSONObject to a Map and then create an Array of keys just use JSONObject.names() for getting all keys in an JsonArray then convert it to Array or ArrayList. example:
JSONObject json = new JSONObject("json object string");
JSONArray namearray=json.names(); //<<< get all keys in JSONArray
Try this:
ArrayList<String> list = new ArrayList<String>();
JSONArray jsonArray = (JSONArray)jsonObject;
if (jsonArray != null) {
int len = jsonArray.length();
for (int i=0;i<len;i++){
list.add(jsonArray.get(i).toString());
}
}
String[] array = list.toArray(new String[list.size()]);

How to convert array of value objects to json?

I have an array of classes of this type:
public class IndexVO {
public int myIndex;
public String result;
}
And this is my array:
IndexVo[] myArray = { indexvo1, indexvo2 };
I want to convert this array to json, any idea how?
This wouldn't be as easy as JSONArray mJSONArray = new JSONArray(Arrays.asList(myArray)) since your array contains objects of unsupported class. Hence you will have to make a little more effort:
JSONArray mJSONArray = new JSONArray();
for (int i = 0; i < myArray.length; i++)
mJSONArray.put(myArray[i].toJSON());
And add toJSON() method to your IndexVo class:
public JSONObject toJSON() {
JSONObject json = new JSONObject();
...
//here you put necessary data to json object
...
return json;
}
However, if you need to generate JSON for more than one class, then consider libraries which do it automatically, flexjson, for example.

Categories

Resources