How to pass bulk of json objects into Json array - android

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.

Related

Convert Arraylist of HashMaps to Json String (GSON)

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

JSON parsing assitance

I can log the JSON file in my app but I'm having troubles parsing the JSON file. I'm trying to get the name of each recipe so I can display it in a RecyclerView. I do need more data from the JSON later on, would it be better to do all the parsing at once or as needed?
Here is the link to the JSON
https://d17h27t6h515a5.cloudfront.net/topher/2017/May/59121517_baking/baking.json
JSONObject recipeObject = new JSONObject(jsonString);
JSONArray recipeResults = recipeObject.getJSONArray("name");
Log.d(LOGTAG, "Recipe Results " + recipeResults.toString());
This is the log result
2018-12-13 13:56:43.622 31472-31472/com.shawn.nichol.bakingapp W/System.err: at com.bakingapp.Data.ExtractRecipeData.recipeData(ExtractRecipeData.java:19)
The base object is an array of objects.
Try this:
JSONArray recipes = new JSONArray(jsonString);
for(int i = 0; i < recipes.length(); i++){
JSONObject recipe = recipes.getJSONObject(i);
Log.d(LOGTAG, "Recipe name: " + recipe.getString("name"));
}
first of all you need to use a tool to better understand your json structure I use jsoneditoronline see in the link the preview of your jsonobject
http://jsoneditoronline.org/?id=dac21affd6544a00a553360e2c9fa311
The parsing is better done at first then you pass your data to the RecyclerViewAdapter
this library should help you a lot https://github.com/google/gson
here is a tutorial for gson : https://howtodoinjava.com/apache-commons/google-gson-tutorial-convert-java-object-to-from-json/
Before trying to access name you need to access an item of the array let's say you need to get the name of the first object that is the nutella pie you do like this
JSONArray myJsonArray = new JSONArray(jsonString);
JSONObject recipeObject = myJsonArray.getJSONObject(0);
Log.d(LOGTAG, "Recipe Name" + recipeObject.getString("name").toString());
if you want to convert your JSON into java you need to
Recipe recipe= gson.fromJson(recipeObject.toString(), Recipe.class);
get all the data as so
List<Recipe> recipeList = new ArrayList();
Gson gson = new Gson();
for (int i = 0; i < jsonArray.length(); i++) {
Recipe recipe= gson.fromJson(myJsonArray .get(i).toString(), Recipe.class);
recipeList.add(recipe);
}

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 get the multiple text from string in Android?

I am developing the Android for Xively. I get the following text data and store into string.
{"id":111111177,"title":"G-sensor","private":"true","feed":"https://api.xively.com/v2/feeds/111111177.json","auto_feed_url":"https://api.xively.com/v2/feeds/111111177.json","status":"frozen","updated":"2014-08-05T07:14:29.783670Z","created":"2014-08-01T08:29:17.156043Z","creator":"https://xively.com/users/x22819","version":"1.0.0","datastreams":[{"id":"GPIO1","current_value":"1","at":"2014-08-05T07:14:18.991421Z","max_value":"1.0","min_value":"0.0","tags":["xyz"],"unit":{"type":"G","label":"watts"}},{"id":"GPIO2","current_value":"0","at":"2014-08-05T07:14:29.783670Z","max_value":"1.0","min_value":"0.0","tags":["xyz"],"unit":{"type":"G","label":"watts"}},{"id":"GPIO3","current_value":"1","at":"2014-08-05T06:51:08.165217Z","max_value":"1.0","min_value":"1.0"},{"id":"GPIO4","current_value":"0","at":"2014-08-05T06:51:13.029452Z","max_value":"0.0","min_value":"0.0"},{"id":"GPIO5","current_value":"1","at":"2014-08-05T06:51:20.679123Z","max_value":"1.0","min_value":"1.0"},{"id":"GPIO6","current_value":"0","at":"2014-08-05T06:51:27.057369Z","max_value":"0.0","min_value":"0.0"}],"location":{"domain":"physical"},"product_id":"w8tuBsYf835kYTjDFz9w","device_serial":"DWJAXD6N7VDZ"}
There has id and the current_value in the above data , and I want to get the data of id and the current_value from the above text like following text.
GPIO1 1
GPIO2 0
GPIO3 1
GPIO4 0
GPIO5 1
GPIO6 0
How do I capture the the data of id and the current_value from the above text ?
Can somebody teach me how to do ?
Thank in advance.
Try this:
String resultJSON = "datastreams":[{"id":"GPIO1","current_value":"1","at":"2014-08-05T07:14:18.991421Z","max_value":"1.0","min_value":"0.0","tags":["xyz"],"unit":{"type":"G","label":"watts"}},
{"id":"GPIO2","current_value":"0","at":"2014-08-05T07:14:29.783670Z","max_value":"1.0","min_value":"0.0","tags":["xyz"],"unit":{"type":"G","label":"watts"}},
{"id":"GPIO3","current_value":"1","at":"2014-08-05T06:51:08.165217Z","max_value":"1.0","min_value":"1.0"},
{"id":"GPIO4","current_value":"0","at":"2014-08-05T06:51:13.029452Z","max_value":"0.0","min_value":"0.0"},
{"id":"GPIO5","current_value":"1","at":"2014-08-05T06:51:20.679123Z","max_value":"1.0","min_value":"1.0"},
{"id":"GPIO6","current_value":"0","at":"2014-08-05T06:51:27.057369Z","max_value":"0.0","min_value":"0.0"}],"location":{"domain":"physical"},"product_id":"w8tuBsYf835kYTjDFz9w","device_serial":"DWJAXD6N7VDZ"};
JSONObject jsonRoot = new JSONObject(resultJSON);
JSONArray jsonData = jsonRoot.getJSONArray("Data");
for(int i=0; i<jsonData.lenght;i++) {
JSONObject jsonOBject = jsonData.getJSONObject(i);
Log.d(TAG, "json ("+i+") = "+jsonOBject.toString());
// do what you want with your JSONObject , i.e :add it to an ArrayList of paresed result
String ID = jsonOBject.getString("id");
}
Hope this may help you
dataList = new ArrayList<HashMap<String, String>>();
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
myarray = jsonObj.getJSONArray("datastreams");
// looping through All myarray
for (int i = 0; i < myarray.length(); i++) {
JSONObject c = myarray.getJSONObject(i);
String id = c.getString("id");
String date = c.getString("at");
// tmp hashmap for single data
HashMap<String, String> data = new HashMap<String, String>();
// adding each child node to HashMap key => value
data.put(TAG_ID, id);
data.put(TAG_DATE, date);
// adding data to data list
dataList.add(data);
}
The data you have is actually a JSON so you can simply parse it to java POJO. I would suggest to use one of 2 most popular open source parsers GSON or Jackson.
What you have to do is:
Create java POJOs for chosen parser. To make it easier use this online tool http://www.jsonschema2pojo.org/
Copy generated java classes to your project.
Use JSON parser e.g. GSON
Let's say you named your main class as Example, with GSON you can parse it like this:
Gson gson = new Gson();
String data = ....//your JSON data
Example example = gson.fromJson(data, Example.class);
Data you would like to get will have own Java representation and will be available through getter method, e.g.:
List<Datastream> datastreams = example.getDatastreamList();
for (DataStream data : datastreams) {
String id = data.getId();
String currentValue = data.getCurrentValue();
}
Then you can do whatever you like. Please know that GSON can also read streams, so if you already parse stream to string you can skip it and pass that stream to Gson object directly.
If you don't want redundant POJOs or their parameters, you can remove them. GSON will handle it and simply ignore these values. Just make sure that data you are interested in keep the generated structure.
That's how I would do it.

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