Creating a JSON from an ArrayList of stings in Android - 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);

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]}}

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.

Which is the best way to parse JSON data in Android?

I have JSON data to parse. The structure is not fixed, and sometimes it comes as a single string and other times as an array.
Currently, we are using the GSON library for parsing JSON, but are facing problems when it comes as an array.
For example:
1. {"msg":"data","c":300,"stat":"k"}
2. {
"msg": [
" {\"id\":2,\"to\":\"83662\",\"from\":\"199878\",\"msg\":\"llll\",\"c\":200,\"ts\":1394536776}"
],
"c": 200,
"stat": "k",
"_ts": 1394536776
}
In the example above, sometimes I get msg as a string and sometimes as an array.
Can anyone help me? If I decide to use JSON parsing, it will be very tedious because I have around 20+ API to parse and each API contains a mininum of 50 fields.
You can use JSONObject and JSONArray classes instead of GSON to work with JSON data
for the first example
String jsonStr = "{\"msg\":\"data\",\"c\":300,\"stat\":\"k\"}";
JSONObject jsonObj = new JSONObject(jsonStr);
String msg = jsonObj.getString("msg");
Integer c = jsonObj.getInteger("c");
String stat = jsonObj.getString("stat");
For the second example
String jsonStr = ... // "your JSON data";
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray jsonArr = jsonObj.getJSONArray("msg");
JSONObject arrItem = jsonArr.getJSONObject(0);
//and so on
Also JSONObject class have method opString, opArray which does not throw exception if data you trying to get is not exist or have a wrong type
For example
JSONArray arr = jsonObj.optJSONArray("msg");
JSONObject msg = null;
if (arr != null) {
msg = arr.getJSONObject(0)
} else {
msg = jsonObj.getJSONObject("msg");
}
You can use Google GSON lib for directly parse the json to class object. This is easy and accurate.Okay do one thing both time code is different, if the code is 300 directly parse the json object without GSON. if the code is 200 the use the GSON (Define the similar java class)
String c= json.getString("c");
if(c.equals("300")
String message = status.getString("msg");
There are two ways to parce JSON.
Manually using Android OS JSON Parser Android JSON Parsing And Conversion
Using GSON Library [Library] (https://code.google.com/p/google-gson/downloads/list). This easy to handle if you know all the parameters and models of json response.
Refer the code snippet below to deserialize your json using Google's Gson library without exceptions.
String jsonStr = "your json string ";
Gson gson = new Gson();
JsonObject jsonObj = gson.fromJson (jsonStr, JsonElement.class).getAsJsonObject();
JsonElement elem = jsonObj.get("msg");
if(elem.isJsonArray()) { //**Array**
ArrayList<MyMessage> msgList = gson.fromJson(elem.toString(), new TypeToken<List<MyMessage>>(){}.getType());
} else if(elem.isJsonObject()) { //**Object**
Note note = gson.fromJson(elem.toString(), MyMessage.class);
} else { //**String**
String note = elem.toString();
}
MyMessage class
public class MyMessage {
String to;
String from;
String msg;
int id;
int c;
long ts;
// Setters and Getters
}

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)

Categories

Resources