storing json parsed values as string in array - android

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

Related

how can I collect the array heroes in my android studio project below

my function is
public String[] loadIntoListView(String json) throws JSONException {
JSONArray jsonArray = new JSONArray(json);
String[] heroes = new String[3];
for (int i = 0; i < 3; i++)
{
JSONObject obj = jsonArray.getJSONObject(i);
// heroes[i] = obj.getString("name");
heroes[i]= "https://static.pexels.com/photos/1543/landscape-nature-man-person-medium.jpg";
}
return heroes;
}
this is where i called it but it is returning null array for me
String s="";
try {
items= loadIntoListView(s);
} catch (JSONException e) {
e.printStackTrace();
}
The line JSONArray jsonArray = new JSONArray(json); may be crashing due to json not being a valid json array. This would cause the array to be null, as it hasn't been initialized yet.
Your exception handler out of for. If you catch exceptions in for body, you can parse verified json items. If a item not correct, you can pass.
For example,
public String[] loadIntoListView(String json) {
JSONArray jsonArray = new JSONArray(json);
ArrayList<String> heroes = new ArrayList();
for (int i = 0; i < jsonArray.length; i++)
{
try{
JSONObject obj = jsonArray.getJSONObject(i);
heroes.add(obj.getString("name"));
}catch(JSONException ignore_errors){
}
}
return heroes.toArray(new String[0]);;
}

How to break up string response?

I am receiving a String response from the following #Override method
#Override
publc void onSuccess(String response) {
....
}
The conflict I am facing is that I do not know how to break up this response into key value pairings. This is an example of the response.
{"action":{"generic_message":"test generic message"},"domains":{"key_example_one":"https:/google.com","api_root_url":"https://test.com/new/0.2/json"},"page":null}}
I have attempted to convert the string to a JSONObject, and then adding the JSONObjects to a JSONArray.
JSONObject mJObj;
try {
mJObj = new JSONObject(response);
JSONArray mJArry = mJObj.getJSONArray("action");
for (int i = 0; i < mJArry.length(); i++) {
JSONObject newObj = mJArry.getJSONObject(i);
String test2 = newObj.getString("generic_example_for_all_platforms");
}
} catch (JSONException e) {
e.printStackTrace();
}
EDIT: I am getting JSON exception that JSONArray cannot be converted to JSONObject, for the following line.
JSONArray mJArry = mJObj.getJSONArray("action");
Thanks in advante
You do want to read more about JSON here.
The first thing to know is that {} is equal to a Json Object and [] is equal to a Json Array.
try {
JSONObject mJObj = new JSONObject(response);
JSONObject actionJsonObject = mJObj.getJSONObject("action");
String generic_message = actionJsonObject.getString("generic_message");
JSONObject domainsJsonObject = mJObj.getJSONObject("domains");
String key_example_one = domainsJsonObject.getString("key_example_one");
String api_root_url = domainsJsonObject.getString("api_root_url");
String page = mJObj.getString("page");
} catch (JSONException e) {
e.printStackTrace();
}
Check out Gson.
JsonObject jsonObject = new JsonParser().parse(jsonString).getAsJsonObject();
EDIT:
Just saw that you can't move to other Json processors. The property 'action' holds a JSONObject not a JSONArray. What about JSONObject jsonObject = mJObj.getJSONObject("action").

ANDROID : How to use org.json.JSONArray in for loop

I use library JsonHttpResponseHandler
and this my code
Data JSON is =
[{"id":"4","2":"123","phone":"123","1":"Shin","0":"4","name":"Shin"},{"id":"5","2":"555","phone":"555","1":"Wolf","0":"5","name":"Wolf"},{"id":"6","2":"666","phone":"666","1":"Lunar","0":"6","name":"Lunar"}]
And this my code =
#Override
public void onSuccess(int statusCode, org.apache.http.Header[] headers, org.json.JSONArray response)
Question is how can i use response data in for loop
Use below code ,
for (int i = 0; i < response.length(); i++) {
try {
JSONObject jobj = response.getJSONObject(i);
String id = jobj.getString("id");
String two = jobj.getInt("2");
String phone = jobj.getInt("phone");
String one = jobj.getInt("1");
String zero = jobj.getInt("0");
String name = jobj.getString("name");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
it is the same as array.
for(int i =0 ; i < response.length() ; i++){
JSONObject object = response.getJSONObject(i);
}
inside json array > jsonobject it is like using a List
for your reference : JSON Array iteration in Android/Java
String dataStr="[{\"id\":\"4\",\"2\":\"123\",\"phone\":\"123\",\"1\":\"Shin\",\"0\":\"4\",\"name\":\"Shin\"},{\"id\":\"5\",\"2\":\"555\",\"phone\":\"555\",\"1\":\"Wolf\",\"0\":\"5\",\"name\":\"Wolf\"},{\"id\":\"6\",\"2\":\"666\",\"phone\":\"666\",\"1\":\"Lunar\",\"0\":\"6\",\"name\":\"Lunar\"}]";
try {
JSONArray jsonStrs =new JSONArray("1111");
for(int i=0;i<jsonStrs.length();i++)
{
JSONObject jobj=jsonStrs.getJSONObject(i);
int id=jobj.getInt("id");
String phone=jobj.getString("phone");
//get other values
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

How do I pull the string array from this json object?

I am trying to get a list of available numbers from the following json object, using the class from org.json
{
"response":true,
"state":1,
"data":
{
"CALLERID":"81101099",
"numbers":
[
"21344111","21772917",
"28511113","29274472",
"29843999","29845591",
"30870001","30870089",
"30870090","30870091"
]
}
}
My first steps were, after receiving the json object from the web service:
jsonObj = new JSONObject(response);
jsonData = jsonObj.optJSONObject("data");
Now, how do I save the string array of numbers?
use:
jsonObj = new JSONObject(response);
jsonData = jsonObj.optJSONObject("data");
JSONArray arrJson = jsonData.getJSONArray("numbers");
String[] arr = new String[arrJson.length()];
for(int i = 0; i < arrJson.length(); i++)
arr[i] = arrJson.getString(i);
you need to use JSONArray to pull data in an array
JSONObject jObj= new JSONObject(your_json_response);
JSONArray array = jObj.getJSONArray("data");
Assuming that you are trying to get it in a javascript block, Try something like this
var arrNumber = jsonData.numbers;
My code is for getting "data":
public void jsonParserArray(String json) {
String [] resultsNumbers = new String[100];
try {
JSONObject jsonObjectGetData = new JSONObject(json);
JSONObject jsonObjectGetNumbers = jsonObjectGetData.optJSONObject("results");
JSONArray jsonArray = jsonObjectGetNumbers.getJSONArray("numbers");
for (int i = 0; i < jsonArray.length(); i++) {
resultsNumbers[i] = jsonArray.getString(i);
}
} catch (JSONException e) {
e.printStackTrace();
Log.e(LOG_TAG, e.toString());
}
}

get many value from json

I need to get latitude and longitude to my android, it got many values like this :
I tried this to get values from JSON :
ArrayList<String> longitude;
ArrayList<String> latitude;
public void parseJson(String result) {
try {
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject jo = jArray.getJSONObject(i);
latitude.add(jo.getString("Latitude").toString());
longitude.add(jo.getString("Longitude").toString());
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
}
But When I check the size of array, it's empty.
Anyone can help or suggest my wrong ? Thanks
#after modified,I still got 0 size of array. So,I tried to search where it's stop by Toast then I found :
public void parseJson(String result) throws JSONException {
longitude = new ArrayList<String>();
latitude = new ArrayList<String>();
JSONArray jArray = (JSONArray)JSONValue.parse(result);
for (Object obj: jArray) {
JSONObject jo = (JSONObject)obj;
//here is when I toast it's got nothing
latitude.add(jo.get("Latitude").toString());
longitude.add(jo.get("Longitude").toString());
}
}
#aroth I got an answer!! I back to use my way like this :
public void parseJson(String result) throws JSONException {
longitude = new ArrayList<String>();
latitude = new ArrayList<String>();
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject jo = jArray.getJSONObject(i);
latitude.add(jo.getString("Latitude").toString());
longitude.add(jo.getString("Longitude").toString());
}
I think I forgot declare these:
longitude = new ArrayList<String>();
latitude = new ArrayList<String>();
I still no idea why your code is not work. However, thank a lot for your help :))
The json.org library is needlessly obtuse with its get<Type> methods that all pointlessly throw JSONException, I would recommend switching to simple-json. Then you could do:
ArrayList<String> longitude;
ArrayList<String> latitude;
public void parseJson(String result) {
longitude = new ArrayList<String>();
latitude = new ArrayList<String>();
JSONArray jArray = (JSONArray)JSONValue.parse(result);
for (Object obj : jArray) {
JSONObject jo = (JSONObject)obj;
latitude.add(jo.get("Latitude").toString());
longitude.add(jo.get("Longitude").toString());
}
}
//a simple test case
public static void main(String[] args) {
String json = "[{\"Latitude\": \"1.23\", \"Longitude\": \"1.23\"}, \n{\"Latitude\": \"1.23\", \"Longitude\": \"1.23\"}, \n{\"Latitude\": \"1.23\", \"Longitude\": \"1.23\"}]";
MyParser parser = new MyParser();
parser.parseJson(json);
//should print: 3, 3
System.out.println(parser.latitude.size() + ", " + parser.longitude.size());
}
Should work, assuming your input JSON matches your example snippet.
try using gson library. It's compact and fast.
https://sites.google.com/site/gson/gson-user-guide

Categories

Resources