How to fetch unique results from json response using andorid.
Hi, i need to fetch data from json webservice, i have read all data's in the json. but i need to store unique value from json.
Is it possible to fetch unique value from json?
First, json is malformated:
{ "lastyear": [ { "order": "96 36 08", "year": "2015", "Text": "No" }, { "order": "03 59 03", "year": "2014", "Text": "No" }, { "order": "16 50 58", "year": "2014", "Text": "No" } ]}
To parse this array, you need implement like this
import org.json.*;
import java.util.ArrayList;
public class MyObject {
private ArrayList<Lastyear> lastyear;
public MyObject () {
}
public MyObject (JSONObject json) {
this.lastyear = new ArrayList<Lastyear>();
JSONArray arrayLastyear = json.optJSONArray("lastyear");
if (null != arrayLastyear) {
int lastyearLength = arrayLastyear.length();
for (int i = 0; i < lastyearLength; i++) {
JSONObject item = arrayLastyear.optJSONObject(i);
if (null != item) {
this.lastyear.add(new Lastyear(item));
}
}
}
else {
JSONObject item = json.optJSONObject("lastyear");
if (null != item) {
this.lastyear.add(new Lastyear(item));
}
}
}
public ArrayList<Lastyear> getLastyear() {
return this.lastyear;
}
public void setLastyear(ArrayList<Lastyear> lastyear) {
this.lastyear = lastyear;
}
}
And the sub-object:
import org.json.*;
public class Lastyear {
private String order;
private String year;
private String text;
public Lastyear () {
}
public Lastyear (JSONObject json) {
this.order = json.optString("order");
this.year = json.optString("year");
this.text = json.optString("Text");
}
public String getOrder() {
return this.order;
}
public void setOrder(String order) {
this.order = order;
}
public String getYear() {
return this.year;
}
public void setYear(String year) {
this.year = year;
}
public String getText() {
return this.text;
}
public void setText(String text) {
this.text = text;
}
}
How to use it:
MyObject object = new MyObject(new JSONObject("YOUR_JSON"));
//Verifiy if object.getLastyear != null
int sizeList = object.getLastyear().size;
for(int i = 0; i < sizeList;i++){
LastYear lastYear = object.getLastyear().get(i)
Log.e("App",lastYear.getYear);
}
To have only unique value, you can use :
private static String[] arrRemove(String[] strArray) {
Set<String> set = new HashSet<String>();
set.addAll((List<String>) Arrays.asList(strArray));
return (String[]) set.toArray(new String[set.size()]);
}
pls try this code
private void readJson(JSONObject jobj) {
ArrayList<String> list=new ArrayList<String>();
JSONArray jsonArray = jobj.getJSONArray("lastyear");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
String year=obj.getString("year");
if (!list.contains(year)) {
list.add(year);
}
}
System.out.println("FirstActivity.readJson()"+list);
}
JSON.