How to post data in my json format - android

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.

Related

How do I remove these "(commas) of the JsonObject?

This is my JsonObject
{"Table":"[{\"FailureIds\":\"\",\"SuccessIds\":\"1167, 8789, 10764, 11935, 937, 938, 939, 940, 3980, 3981, 3982, 3983, 3984, 3985, 3986, 3987, 3988, 3989, 3990, 3991, 6045, 6046, 6047, 6048, 6049, 6050, 6051, 7453, 7454, 7455, 7456, 7457, 8559, 8560, 8561, 8562, 10432, 10433, 10434, 10435, 10436, 10437, 10438, 11705, 11706, 11707, 11708\"}]"}
I need to get rid of the starting " and ending " from [{ and after }]
I have already tried with JsonElement as below with no success.
String temp="["+successIds.toString()+"]";
JsonObject jsonObjec=new JsonObject();
Gson gson3 = new Gson();
JsonElement jsonElement = gson3.toJsonTree(temp);
jsonObjec.add("Table",jsonElement);
The successIDs was a JSONobject containing failureIDs and SuccessIDs which I converted to String.
Refer the code snippet below to create your JSON using Google's Gson library without extra quotes.
Gson gson = new Gson(); //Creates Gson Object
JsonObject jsonObject = new JsonObject();
jsonObject.add("FailureIds", gson.toJsonTree(FailureIds)); //Adding array of failure ids to inner object
jsonObject.add("SuccessIds", gson.toJsonTree(SuccessIds)); //Adding array of success ids to inner object
JsonObject finalObject = new JsonObject();
finalObject.add("Table", gson.toJsonTree(jsonObject));
String jsonStr = gson.toJson(finalObject); //Converts final object to valid Json string
Final Json will look like
{"Table": {"FailureIds":[1,2,5], "SuccessIds":[4,6,7]}}

JSON object building

Currently I have this JSON structure:
{"title1":["info1","info2"],"title2":"info2","title3":"info3"}
What I need to achieve is this:
{"title4":[{"a":"aa","b": "bb"}]}
To achieve the above, I use JSONArray:
JSONArray list = new JSONArray();
list.put("info1");
list.put("info2");
obj.put("title1", list);
And JSONObject:
JSONObject obj = new JSONObject();
obj.put("title2", "info2");
How can I visualize the desired output?
To achieve what you want, a JSONObject with a JSONArray containing JSONObjects, you can use the following code
JSONObject root = new JSONObject(); // The root JSON object
JSONArray title4 = new JSONArray(); // The JSON array that will contain JSON objects
// The JSON objects
JSONObject a = new JSONObject();
a.put("a", "aa");
JSONObject b = new JSONObject();
b.put("b", "bb");
title4.put(a);
title4.put(b);
// Put the JSON array in the root JSON object
root.put("title4", title4);

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)

Creating a JSON from an ArrayList of stings in Android

I have an array of string:
a = ["bob","jade","smith"]
I want to convert this to a JSON output like the following in my Android application, this data needs to be sent to the server.
{"names":["bob","jade","smith"]}
Plz help.
I have tried this:
Gson abs = new Gson();
String data = abs.toJson(a);
JSONObject jObjectType = new JSONObject();
jObjectType.put("names",data);
data=jObjectType.toString();
This is my output on the log:
{"names":"[\"bob\",\"jade\",\"smith\"]"}
JSONArray names = new JSONArray(Arrays.asList(a));
JSONObject jsonToSend = new JSONObject();
jsonToSend.put("names", names);
Look into Gson, this library allows you to convert any object to JSON format, and back to the same object once you receive the JSON.
(Serialization)
Gson gson = new Gson();
int[] values = { 1 };
gson.toJson(values); ==> prints [1]
(Deserialization)
int one = gson.fromJson("1", int.class);
Integer one = gson.fromJson("1", Integer.class);
Long one = gson.fromJson("1", Long.class);
Boolean false = gson.fromJson("false", Boolean.class);
String str = gson.fromJson("\"abc\"", String.class);
String anotherStr = gson.fromJson("[\"abc\"]", String.class);

Categories

Resources