I am rather new to JSON at the moment, but I need to convert a JSON response that contains the same key, but different values to an ArrayList to use it with my spinner.
I tried it like here: Converting JSONarray to ArrayList
But i get the whole json string, but just need the value part.
I can't figure out how to do this and found no answer that worked for me :/
What I want would be a List like:
City1
City2
City3
But i have in my spinner:
{"city":"name1"}
{"city":"name2"}
{"city":"name3"}
Code I have is:
JSONArray obj = new JSONArray(response);
Spinner availableCitySpin;
availableCitySpin = (Spinner) findViewById(R.id.avCitySp);
List<String> cityValues = new ArrayList<String>();
if (jarr != null) {
for (int i=0;i< jarr.length();i++){
cityValues.add(jarr.getString(i).toString());
}
}
ArrayAdapter<String> cityAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, cityValues);
cityAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
availableCitySpin.setAdapter(cityAdapter);
availableCitySpin.setSelection(0);
Change your code to something like this:
...
for (int i=0;i< jarr.length();i++){
JSONObject cityObject = jarr.getJSONObject(i);
cityValues.add(cityObject.getString("city"));
}
...
Try this:
First use split
For example: String[] result = splits[0].split(":");
you will get two item in array result. result[0]= {"city" and result[1] = "name1"}
If you want to get the key use result[0]
remove sign from result[0] using replace. Example: data = result[0].replace("\"","").replace("{","");
use it in loop, should work
We have an Array List consisting of many strings.
public final static ArrayList<String> MyListArrayList= new ArrayList<String>(){{}};
And we converted the array list into a comma separated string using below code
gson = new Gson();
listOfTestObject = new TypeToken<ArrayList<String>>(){}.getType();
MyListString = gson.toJson(Images.MyListArrayList, listOfTestObject);
Now we have a comma separated string like
"Item1,Item2,Item3,Item3.....Itemn"
and we are saving this string using the preference whenever the array list gets updated. So now we need to load this string at starting and then convert the string back into the array List.For that we are trying below code
List<String> Images.MyListArrayList= new ArrayList<String>(Arrays.asList(s.split(",")));
But its not possible to do it.But we can create a new List.. But we want to update the already existing Array List instead of creating new one. How to do it?
String value="Item1,Item2,Item3,Item3.....Itemn";
String[] arrayList = value.split(",");
ArrayList list = new ArrayList<String>();
for (int i = 0; i < arrayList.length; i++) {
list .add(arrayList[i]);
}
Hi the below is my response from format
object {6}
csdfgi_fgid : 4casdff9743a1-3f9asdf2-4
fesdfgedVsdfgersionsfdg : 7
sdfg : 28
feesdfgdStart : 0
fesdfedCsdfgoudfsgnt : 28
discover[28]
0{4}
DiscCat : Tip
templateCat{2}
name : tip.tp
version : 2
timestamp : 1421146871251
content{1}
I am getting these values using Serializable in class like below
#SerializedName("csdfgi_fgid")
public String sCdfsisdfId;
#SerializedName("feedVersion")
public Long lFesdfgedVsdfgfsersdfsion;
#SerializedName("feed")
public ArrayList<DiscoverModel> discover;
Now in the array list again there is a Json Object "templateCat" which has two parameters "name , version". Now how to get values from this JSON Object
First of all you need to assign all the JSONObject that you are getting in a POJO class. After that getting JSONObject(templateCat) from JSONArray(discover) you have to do looping. For example:
for(int i=0;i<discover.size();i++){
TemplateCat templateCat = discover.get(i).getTemplateCat();
String strName = templateCat.getName();
String strVersion = templateCat.getVersion();
//If you want to get all name and version as list. Add strName and strVersion to ArrayList. <br>
For Example : nameArray.add(strName);
versionArray.add(strVersion);
}
You'll have to get that JSON array first, iterate thru it and then use Gson to convert it into your desired object.
JSONObject rootJson = /* Get your JSON object here */;
JSONArray nestedArray = rootJson.getJsonArray("your_nested_json_array_name");
List<YourObject> objects;
for(int i = 0; i < nestedArray.size(); i++) {
String objectJsonString = nestedArray.get(i);
YourObject o = new Gson().fromJson(objectJsonString, YourObject.class);
objects.add(o);
}
..the last thing you'd need to do is to set our objects list to your desired instance.
Can anybody please explain me how to set two items of the same category at a time from json into android dropdown(Spinner) using adapter.
josn data:
{"categories":[{"id":"1","name":"Beverages"},{"id":"2","name":"Bread"},{"id":"3","name":"Cereals"},{"id":"4","name":"Cheese"},{"id":"5","name":"Citrus Fruits"}]}
Following is code I'am using to set only one item into spinner:
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//Firstly you need to parse your json for that json response convert into string
ArrayList<String> list =new ArrayList<String>();
String response ={"categories":[{"id":"1","name":"Beverages"},{"id":"2","name":"Bread"},{"id":"3","name":"Cereals"},{"id":"4","name":"Cheese"},{"id":"5","name":"Citrus Fruits"}]}
JSONObject resJsonObj =new JSONObject(response);
JSONArray arrayData=resJsonObj.getJSONArray("categories");
for (int i = 0; i < arrayData.length(); i++) {
temp="";
JSONObject arrayObj = arrayData.getJSONObject(i);
temp=arrayObj.getString("name");
//temp=arrayObj.getString("id");
list.add(temp);
}
This list pass in your array adapter as You need
you can also make a Array list generic type according to your bean class if you
want to get all element from json id
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.