Generate JSONObject dynamically in android - android

I want to generate the following form
{
"dt": {
"DocumentElement": [
{
"CompanyID": "8",
"Question": "Who I M?",
"Answer": "dfsfdsfd"
},
{
"CompanyID": "8",
"Question": "Who I M?",
"Answer": "Chintan"
}
]
}
}
I have one arraylist which is dynamically filled with data and i also want the form in terms of dynamic. Here is my code:
JSONObject DocumentElementobj = new JSONObject();
JSONArray req = new JSONArray();
JSONObject reqObj = new JSONObject();
try {
for (int i = 0; i < OnLineApplication.mParserResults.size(); i++) {
reqObj.put("CompanyID", "8");
reqObj.put("Question",OnLineApplication.mParserResults.get(i).getQuestion());
reqObj.put("Answer",OnLineApplication.mParserResults.get(i).getAnswer());
}
DocumentElementobj.put( "DocumentElement", req );
System.out.println("Final "+DocumentElementobj.toString());
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
It outputs:
Final {"DocumentElement":[]}
EDIT
Thanks to all your response. As per you all responce i make code like below
JSONObject DocumentElementobj = new JSONObject();
JSONArray req = new JSONArray();
JSONObject reqObjdt = new JSONObject();
try {
for (int i = 0; i < OnLineApplication.mParserResults.size(); i++) {
JSONObject reqObj = new JSONObject();
reqObj.put("CompanyID", OnLineApplication.mParserResults.get(i).getCompanyId());
reqObj.put("Question",OnLineApplication.mParserResults.get(i).getQuestion());
reqObj.put("Answer",OnLineApplication.mParserResults.get(i).getAnswer());
req.put(reqObj);
}
DocumentElementobj.put( "DocumentElement", req );
reqObjdt.put("dt", DocumentElementobj);
System.out.println("Final "+reqObjdt.toString());
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
I get foramt which i want but in final string i get sequeence like below
{"dt":
{"DocumentElement":
[
{"Answer": "The Claims Representatives have a small role in return to work.","Question":"Return-to-Work Claim Issues. Please check the statement that best applies.","CompanyID":"8"},
{"Answer":"Poor","Question":"How would you describe the level of your general employee’s understanding of the impact of workers’ compensation costs on your organization?","CompanyID":"8"}]}}
it comes Answer first in sequence but i want to CompanyID first so what is issue in that?

You forgot to add JSONObject reqObj into JSONArray req. like req.put(reqObj);.
Modify your code block from for loop like
JSONObject reqObj = new JSONObject(); // Move inside the loop
reqObj.put("CompanyID", "8");
reqObj.put("Question",OnLineApplication.mParserResults.get(i).getQuestion());
reqObj.put("Answer",OnLineApplication.mParserResults.get(i).getAnswer());
req.put(reqObj); // ADDED HERE

You don't add the reqObj to req.
Do req.put(reqObj)
JSONObject documentElementobj = new JSONObject();
JSONArray req = new JSONArray();
try {
for (int i = 0; i < OnLineApplication.mParserResults.size(); i++) {
JSONObject reqObj = new JSONObject();
reqObj.put("CompanyID", "8");
reqObj.put("Question",OnLineApplication.mParserResults.get(i).getQuestion());
reqObj.put("Answer",OnLineApplication.mParserResults.get(i).getAnswer());
req.put(reqObj);
}
documentElementobj.put( "documentElement", req );
System.out.println("Final "+ documentElementobj.toString());
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Also, it is better to make your variables begin with a lowercase letter, usually.
One more thing, using a debugger will be effective in this case.

There is a very good Google Libray called gson which help you to create Json Object or Parse Json Object with very ease.
You need to add gson.jar file in your project.
For More details go through the below link.
https://sites.google.com/site/gson/gson-user-guide
Edited Answer:-
public class DocumentElement {
#Expose
private String CompanyID;
#Expose
private String Question;
#Expose
private String Answer;
public DocumentElement(String CompanyID, String Question, String Answer) {
this.CompanyID = CompanyID;
this.Question = Question;
this.Answer = Answer;
}
public String getCompanyID() {
return CompanyID;
}
public String getQuestion() {
return Question;
}
public String getAnswer() {
return Answer;
}
}
public class Data {
#Expose
private ArrayList<DocumentElement> DocumentElement;
public ArrayList<DocumentElement> getDocumentElement() {
return DocumentElement;
}
public void setDocumentElement(ArrayList<DocumentElement> DocumentElement) {
this.DocumentElement = DocumentElement;
}
}
public class ParentData {
#Expose
private Data dt;
public Data getDt() {
return dt;
}
public void setDt(Data dt) {
this.dt = dt;
}
}
And used like this to create JsonObject by help of gson.jar
ArrayList<DocumentElement> doc=new ArrayList<DocumentElement>();
DocumentElement doc1=new DocumentElement("8", "Who I M?", "Amit");
DocumentElement doc2=new DocumentElement("9", "Who I M?", "Gupta");
doc.add(doc1);
doc.add(doc2);
Data data=new Data();
data.setDocumentElement(doc);
ParentData parent=new ParentData();
parent.setDt(data);
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
String jsonObj = gson.toJson(parent);
System.out.println("createdJson:---"+jsonObj);
The Result are
{"dt":{"DocumentElement":[{"Answer":"Amit","CompanyID":"8","Question":"Who I M?"},{"Answer":"Gupta","CompanyID":"9","Question":"Who I M?"}]}}
Hope this will help you.

Use this code to fullfill your answer :
JSONObject jObj = new JSONObject("Your web Response");
JSONObject jObj1 = jObj.getJSONObject("dt");
JSONArray item = jObj.getJSONArray("DocumentElement");
for (int i = 0; i < item.length(); i++)
{
jObj_data = (JSONObject) item.get(i);
reqObj.put("CompanyID", jObj_data.getString("CompanyID"));
reqObj.put("Question",jObj_data.getString("Question"));
reqObj.put("Answer",jObj_data.getString("Answer"));
}

Related

How do I get a list of Countries, States and Cities from this JSON?

I have a JSON that contains the names of Countries, their states and cities of those states. Here is the json.
I am able to get all the countries but I can't figure out how to get the states based on the selected country and then cities based on the selected state.
Here is how I got the countries.enter code here
First to load the file from assets:
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = getAssets().open("Contries.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
Then to load the countries into an ArrayList.
public void loadCountries(String parent, String child, ArrayList<String> listValue)
{
try {
JSONObject obj = new JSONObject(loadJSONFromAsset());
JSONArray m_jArry = obj.getJSONArray(parent);;
ArrayList<HashMap<String, String>> formList = new ArrayList<HashMap<String, String>>();
HashMap<String, String> m_li;
// listValue = new ArrayList<>();
for (int i = 0; i < m_jArry.length(); i++) {
JSONObject jo_inside = m_jArry.getJSONObject(i);
listValue.add(jo_inside.getString(child));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Then this line finally:
loadCountries("Countries", "CountryName", countries);
After I have selected a country, I want to load its states. maybe something like this:
loadCountries("Pakistan", "StateName", states);
and then:
loadCountries("Islamabad Capital Territory", "CityName", cities);
Any help is greatly appreciated.
Working with JSON can be error-prone. Why don't we model objects around your data and we can do something a little more clearer.
Overview.
Lets' Model your objects
Let's Deserialize your raw json into "Objects"
Then we can "query" our modelled objects!
Step 1 - Modelling.
Note I'm not including constructors, getters, setters and any other boiler plate.
public class Country {
private List<State> states;
private String name;
public Optional<State> getStateByName(String name) {
return States.stream().filter(state -> state.getName().equals(name)).findFirst();
}
}
public class State {
private List<String> cities;
private String name;
public Optional<String> getCityByName(String name) {
return cities.stream().filter(city -> city.equals(name)).findFirst();
}
}
public class CountryDataProvider {
private List<Country> countries;
public CountryDataProvider(String rawData) {
// parse your json to create a List of object Country (tip: Use something like Jackson or Gson to do this for you).
// Ref to part 2
}
public Optional<Country> getCountryByName(String name) {
return countries.stream().filter(country -> country.getName().equals(name)).findFirst();
}
}
Step 2 - Deserialize.
This is a broad topic and To be honest there is a lot of libraries that will do it better and they are really easy to add to your project. Here are a few:
Jackson https://github.com/FasterXML/jackson
GSON https://github.com/google/gson <- My pick.
Step 3 - Query
From here you can do what ever you want
countryData = new CountryDataProvider(data);
Optional<List<String>> countriesInPunjab = countryData.getCountryByName("Pakistan")
.map(country -> country.getStateByName("Punjab")
.map(state -> state.getCities()); // would give you all the cities in Punjab, Pakistan.
The code I have given in my example does use functional and Optional interfaces (in Java 8). Let me know if you want them rewritten in a less functional way.
Here is another solution, not very CPU friendly but it works:
First use this method to get a list of countries:
public void loadCountries(String parent, String child, ArrayList<String> listValue)
{
try {
JSONObject obj = new JSONObject(loadJSONFromAsset());
JSONArray m_jArry = obj.getJSONArray(parent);
// m_jArry;
ArrayList<HashMap<String, String>> formList = new ArrayList<HashMap<String, String>>();
HashMap<String, String> m_li;
// listValue = new ArrayList<>();
for (int i = 0; i < m_jArry.length(); i++) {
JSONObject jo_inside = m_jArry.getJSONObject(i);
listValue.add(jo_inside.getString(child));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Call this method like this:
loadCountries("Countries", "CountryName", countries);
Then use the following method to load the States and Cities.
private void getCitiesByState(String countryName, String stateName)
{
try {
JSONObject json = new JSONObject(loadJSONFromAsset());
JSONArray countriesArray = json.getJSONArray("Countries");
for(int i = 0; i < countriesArray.length(); i++)
{
JSONObject countryJSON = countriesArray.getJSONObject(i);
if(countryJSON.getString("CountryName").equals(countryName))
{
JSONArray statesArray = countryJSON.getJSONArray("States");
states.clear();
for(int j = 0; j < statesArray.length(); j++)
{
JSONObject statesJSON = statesArray.getJSONObject(j);
states.add(statesJSON.getString("StateName"));
if(statesJSON.getString("StateName").equals(stateName))
{
JSONArray citiesarray = statesJSON.getJSONArray("Cities");
cities.clear();
for(int k = 0; k < citiesarray.length(); k++)
{
cities.add(citiesarray.getString(k));
}
}
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}

just only one list on my listview

I have array look like this :
"results":[
{
"code":"jne",
"name":"Jalur Nugraha Ekakurir (JNE)",
"costs":[
{
"service":"OKE",
"description":"Ongkos Kirim Ekonomis",
"cost":[
{
"value":38000,
"etd":"4-5",
"note":""
}
]
},
{
"service":"REG",
"description":"Layanan Reguler",
"cost":[
{
"value":44000,
"etd":"2-3",
"note":""
}
]
},
{
"service":"SPS",
"description":"Super Speed",
"cost":[
{
"value":349000,
"etd":"",
"note":""
}
]
},
{
"service":"YES",
"description":"Yakin Esok Sampai",
"cost":[
{
"value":98000,
"etd":"1-1",
"note":""
}
]
}
]
}
]
My code on android to process array, problem in my code on function "for" before I copy and edit another code from file :
JSONObject jsonObjsko = new JSONObject(rajaongkir);
String resultse = jsonObjsko.getString("results");
JSONArray jsonObjssto = new JSONArray(resultse);
JSONObject mJsonObject = jsonObjssto.getJSONObject(0);
costs = mJsonObject.getString("costs");
JSONArray jsonArray = new JSONArray(costs);
for (int k = 0; k < jsonArray.length(); k++) {
try {
JSONArray jsonArrayp = new JSONArray(costs);
JSONObject jsonObject = jsonArrayp.getJSONObject(k);
String serviceq = jsonObject.getString("cost");
String servicel = jsonObject.getString("service");
kon = String.valueOf(jsonArray.length());
kin = kin + k;
JSONArray jsonObjsstorng = new JSONArray(serviceq);
JSONObject mJsonObjectrng = jsonObjsstorng.getJSONObject(k);
String values = mJsonObjectrng.getString("value");
ShipPerActiv wp = new ShipPerActiv(servicel, values);
arraylist.add(wp);
}
catch (JSONException e) {
e.printStackTrace();
}
}
This code for ShipPerActiv for add arraylist :
public class ShipPerActiv {
private String services;
private String hongkir;
public ShipPerActiv(String services,String hongkir) {
this.services = services;
this.hongkir = hongkir;
}
public String getservices() {return this.services; }
public String gethongkir() {return this.hongkir; }
}
I tried use harddebug with kon & kin true function for normal but not on my listview just one int(0) not int(1)~etc
At first convert your StringObject to JSONObject and dont forget to add { at first of string and } to end of string:
JSONObject parentObject = new JSONObject("{"+"JsonString"+"}");
Then parse your object like this :
try {
JSONObject parentObject = new JSONObject(a);
JSONArray results = parentObject.getJSONArray("results");
JSONObject resultsObject=results.getJSONObject(0);
JSONArray costsArray = resultsObject.getJSONArray("costs");
for (int i = 0; i < costsArray.length(); i++) {
Log.d("CostsJsonObject" , costsArray.getJSONObject(i).toString());
}
} catch (JSONException e) {
Log.d("CostsJsonObject Exception" , e.toString());
}
And result :
I think your problem is on this code :
JSONObject mJsonObjectrng = jsonObjsstorng.getJSONObject(k);
Simply change it to :
JSONObject mJsonObjectrng = jsonObjsstorng.getJSONObject(0);
Hope it'll help you ;)

JSON parsing for an array with two arraylists inside [duplicate]

This question already has answers here:
Parsing JSON object in android
(5 answers)
Closed 4 years ago.
I am trying to parse the following API data. I just have to use the start time, end time, location and event name inside my app. I have never parse this type of data before. Hitting the API URL and getting a response is working fine, I just need help in parsing.
I have tried these solutions but it didn't work.
parsing JSON 2 arrays (embedded) in Android
How to Parsing JSON (Two Dimensional) array Object in android?
How to parse JsonArray and JSON Object having two keys and values in android?
Ask Android parsing JSON multiple arrays.
JSON:
[
{
"end": {
"endDate": "2018-03-09",
"endTime": "03:00",
"_id": "5a901a7d9fee7d156d594b04"
},
"location": "Dance Tent",
"start": {
"startDate": "2018-03-09",
"startTime": "02:00",
"_id": "5a901a7d9fee7d156d594b05"
},
"announcementName": "Jumanji Dance Party"
}
]
Code:
final JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(DATA_URL, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int index = 0; index < response.length(); index++) {
try {
JSONObject jsonObject = response.getJSONObject(index);
String fullName = jsonObject.getString("startTime");
String about = jsonObject.getString("announcementName");
String artistType = jsonObject.getString("endTime");
String link = jsonObject.getString("location");
//String avatar = jsonObject.getString("avatar");
Annoucement_Day_One artistInfoGetter=new Annoucement_Day_One( fullName,about, artistType, link );
annoucementDayOneList.add(artistInfoGetter);
wednesdayAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("ERRROR RES: ", error.toString());
myInstance.dismiss();
}
});
requestQueue.add(jsonArrayRequest);
Try this
try {
JSONArray jsonArray= new JSONArray(response);
for (int i=0;i<jsonArray.length();i++){
JSONObject object=jsonArray.getJSONObject(i);
String location=object.getString("location");
String announcementName=object.getString("announcementName");
JSONObject end=object.getJSONObject("end");
String endDate=end.getString("endDate");
String endTime=end.getString("endTime");
String id=end.getString("_id");
JSONObject start=object.getJSONObject("start");
String startDate=start.getString("startDate");
String startTime=start.getString("startTime");
String start_id=start.getString("_id");
}
} catch (JSONException e) {
e.printStackTrace();
}
Try this ,
for (int index = 0; index < response.length(); index++) {
try {
JSONObject jsonObject = response.getJSONObject(index);
JSONObject startJson = jsonObject.getJSONObject("start");
String startTime = startJson.getString("startTime");
JSONObject endJson = jsonObject.getJSONObject("end");
String endTime = endJson.getString("endTime");
String announcementName = jsonObject.getString("announcementName");
String location = jsonObject.getString("location");
} catch (JSONException e) {
e.printStackTrace();
}
}
ArrayList<Holder1> arrayList = new ArrayList<>();
try {
JSONArray jsonArray = new JSONArray(response);
for(int index = 0 ;index < jsonArray.length() ; index++){
JSONObject jsonObject1 = jsonArray.getJSONObject(index);
//make a holder for end, location, start,announcementName
Holder1 holder = new Holder1();
holder.setLocation(jsonObject1.optString("location"));
holder.setAnnouncementName(jsonObject1.optString("announcementName"));
//------------
JSONObject jsonObjectEnd =jsonObject1.getJSONObject("end");
holder.setEndDate(jsonObjectEnd.optString("endDate"));
holder.setEndTime(jsonObjectEnd.optString("endTime"));
holder.setEndID(jsonObjectEnd.optString("_id"));
//--------------
JSONObject jsonObjectStart =jsonObject1.getJSONObject("start");
holder.setStartDate(jsonObjectStart.optString("startDate"));
holder.setStartTime(jsonObjectStart.optString("startTime"));
holder.setStartID(jsonObjectStart.optString("_id"));
//--------------
arrayList.add(holder);
}
} catch (JSONException e) {
e.printStackTrace();
}
Accept the answer. If you like the way i have written.
You can use the GSON library by google.
add the dependency in build.gradle.
compile 'com.google.code.gson:gson:2.8.0'
First, you have to create the model class for your JSON response. this will help you to create the model class.
public class MyPojo
{
private Start start;
private String location;
private String announcementName;
private End end;
public Start getStart ()
{
return start;
}
public String getLocation ()
{
return location;
}
public String getAnnouncementName ()
{
return announcementName;
}
public End getEnd ()
{
return end;
}
}
--------------Start.Java------------
public class Start
{
private String startTime;
private String startDate;
private String _id;
public String getStartTime ()
{
return startTime;
}
public String getStartDate ()
{
return startDate;
}
public String get_id ()
{
return _id;
}
}
------------End.Java-------------------
public class End
{
private String _id;
private String endDate;
private String endTime;
public String get_id ()
{
return _id;
}
public String getEndDate ()
{
return endDate;
}
public String getEndTime ()
{
return endTime;
}
}
Now in your onResponse method
MyPojo respnse = new Gson().fromJson(response.toString(), MyPojo.class);
you can access any method from response.Ex. response.getEnd().getEnd_date()

Extract and Save Json to Arraylist Android

How can i extract the json below and save it in an arraylist.
{
"trains": {
"train": [
{
"#id": 1000000103,
"#version": 1,
"#status": "active",
"#name": "dffffff",
"#description": "ffffff half of the nineteenth century.",
"#city": "fff",
"#phone": "+230 595-1454",
"#email": "ffffr#mffc.mu",
"#website": "www4u",
"#latitude": -5.2882,
"#longitude": 3.499,
"#defaultLocale": "",
"#holes": 48,
"#par": 72,
"#slope": 0,
"#distance": 5.005273,
"circuits": {
"circuit": []
},
"localizations": {
"localization": []
}
},
{
"#id": 1000000105,
"#version": 1,
"#status": "active",
"#name": " xClub",
"#description": "",
"#city": " xlet",
"#phone": "+44465\t",
"#email": "",
"#website": "wweffl.com",
"#latitude": -2.040318,
"#longitude": 54548,
"#defaultLocale": "",
"#holes": 18,
"#par": 32,
"#slope": 0,
"#distance": 2441673,
"circuits": {
"circuit": []
},
"localizations": {
"localization": []
}
}
]
}
}
my working
try {
jobj_trouve_train = new JSONObject(reponse_trouve_train);
String jsonobj = jobj_trouve_golf.getString("trains");
//String jsonobj1 = jobj_trouve_golf.getString("train");
//jobj_trouve_train = new JSONObject(reponse_trouve_train);
//jsonArray = jobj_trouve_golf.getJSONArray("trains");
//jsonArray= new JSONArray(jsonobj);
//System.out.println("jsonArray "+jsonArray);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Try this..
try {
jobj_trouve_train = new JSONObject(reponse_trouve_train);
JSONObject jsonobj = jobj_trouve_train.getJSONObject("trains");
JSONArray jsonobj1 = jsonobj.getJSONArray("train");
for(int i = 0;i< jsonobj1.length();i++){
JSONObject jsonj = jsonobj1.getJSONObject(i);
System.out.println("#id "+jsonj.getString("#id"));
// Same for remaining all
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
You can use the Gson library developed by Google to parse Json into objects.
The reference is here:
https://code.google.com/p/google-gson/
And, a sample example is here:
JSON Parsing with GSON
JSONObject trains = jobj_trouve_train.getJSONObject("trains");
JSONArray trainArray = trains.getJSONArray("train");
JSONObject train1 = trainArray.getJSONObject(0);
...
if i didn't get confuse maybe this one will be right
JSONArray jasonArray = new JSONArray(result.getProperty("trains").toString());
for (int i = 0; i < jasonArray.length(); i++) {
JSONObject jsonObj = jasonArray.optJSONObject(i);
trainObject = new JSONObject(jsonObj.optString("train").toString());
int id = trainObject.optInt("id");
and so on..
}
public Object void toObject(String jsonMsg) throws JSONException {
JSONObject trains= (JSONObject) new JSONTokener(jsonMsg).nextValue();
if(trains.has("trains")){
JSONArray train = (JSONArray) new JSONTokener(object.getString("train")).nextValue();
for (int t = 0; t < jsonArray.length(); t++) {
String temp = jsonArray.getJSONObject(t).toString();
JSONObject object = (JSONObject) new JSONTokener(temp).nextValue();
if(object.has("#id"))
object.getString("#id");
// now similar procedure of reading
// read values and save it in an "object"
}
return savedObject;
}
-- tested, i have tried to modify code to match your JSON data. complete the rest.

storing json parsed values as string in array

I've got a json object, which is being collected into a function as string.
It contains array
{"officer_name":"V. M. ARORA"}{"officer_name":"Dr. C. P.
REDDY"}{"officer_name":"ARTI CHOWDHARY"}{"officer_name":"JAGDISH
SINGH"}
and here is the android code
public void func4(View view)throws Exception
{
AsyncHttpClient client = new AsyncHttpClient();
RequestParams rp = new RequestParams();
rp.put("pLat", "SELECT officer_name FROM iwmp_officer");
client.post("http://10.0.2.2/conc5.php", rp, new AsyncHttpResponseHandler() {
public final void onSuccess(String response) {
// handle your response here
ArrayList<String> User_List = new ArrayList<String>();
try {
/* here I need output in an array,
and only names not the "officer_name" */
} catch (Exception e) {
tx.setText((CharSequence) e);
}
//tx.setText(User_List.get(1));
}
#Override
public void onFailure(Throwable e, String response) {
// something went wrong
tx.setText(response);
}
});
}
The output I've shown above is in String, need to get it in array. Please help!
If the output you got is something like this.
String outputJson=[{"officer_name":"V. M. ARORA"}{"officer_name":"Dr. C. P. REDDY"}{"officer_name":"ARTI CHOWDHARY"}{"officer_name":"JAGDISH SINGH"}]
Then its a JSON Array.
You can parse it as
JsonArray array=new JsonArray(outputJson);
Then loop this json array using
for(JsonObject jsonObj in array){
String officerName=[jsonObj getString("officer_name");
}
You can use something like above The mentioned code is not correct syntactically but yes conceptually correct. You can go ahead with this.
List < String > ls = new ArrayList< String >();
JSONArray array = new JSONArray( response );
for (int i = 0; i < array.length() ; i++ ) {
JSONObject obj = array.getJSONObject(Integer.toString(i));
ls.add(obj.getString("officer_name"));
}
This would work
try {
JSONArray array= new JSONArray(response);
//array = new JSONArray(response);
for (int i = 0; i < array.length(); i++) {
//JSONObject obj = response.getJSONArray(i);
JSONObject jsonLineItem = (JSONObject) array.getJSONObject(i);
String name_fd = jsonLineItem.getString("officer_name");
User_List.add(jsonLineItem.getString("officer_name"));
Log.d("JSONArray", name_fd+" " +name_fd);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
tx.setText( e.toString());
}

Categories

Resources