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
Related
Iwant to access a jsonArray data in a jsonObjet response code that comes from server. here is my response json
{
event_id: "32",
event_title: "امیر",
event_description: "تست امیر",
event_image: "2_1550507094.jpg",
event_hikers_amount: "9",
event_private: "0",
event_date_start: "17/2/2019",
event_date_end: "21/2/2019",
event_time_start: "21:54",
event_time_end: "12:54",
event_locations_array:
"[
{"latitude":37.58728984572849,"longitude":45.10016608983278},
{"latitude":37.57651702299841,"longitude":45.0880378112197},
{"latitude":37.5753956777439,"longitude":45.1045374199748},
{"latitude":37.564077382844964,"longitude":45.094508975744255},
{"latitude":37.55829758877768,"longitude":45.08105669170619},
{"latitude":37.53919984571198,"longitude":45.09874418377876}
]",
event_latitude_location: "37.587289845728",
event_longitude_location: "45.100166089833",
event_status: "1",
event_users_id: "2"
}
I want to parse "event_locations_array" and what what i done :
#Override
protected void onPostExecute(String result) {
try {
JSONObject jsonObject = new JSONObject(result);
description = jsonObject.getString("event_description");
people_joined = jsonObject.getString("event_hikers_amount");
date_start = jsonObject.getString("event_date_start");
date_end = jsonObject.getString("event_date_end");
time_start = jsonObject.getString("event_time_start");
time_end = jsonObject.getString("event_time_end");
privacy = jsonObject.getString("event_private");
JSONArray jsonArray = jsonObject.getJSONArray("event_locations_array");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject points = jsonArray.getJSONObject(i);
JSONObject lat = points.getJSONObject("latitude");
JSONObject lang = points.getJSONObject("longitude");
}
setTextView();
} catch (JSONException e) {
e.printStackTrace();
}
}
here i can't take that jsonArray. what i did wrong here let me know . I'm a little confused
thanks in advance
Fast solution
If you can not change the JSON generation, simply use this code:
#Override
protected void onPostExecute(String result) {
try {
JSONObject jsonObject = new JSONObject(result);
description = jsonObject.getString("event_description");
people_joined = jsonObject.getString("event_hikers_amount");
date_start = jsonObject.getString("event_date_start");
date_end = jsonObject.getString("event_date_end");
time_start = jsonObject.getString("event_time_start");
time_end = jsonObject.getString("event_time_end");
privacy = jsonObject.getString("event_private");
// 1 - fix string to array conversion
JSONArray jsonArray = new JSONArray(jsonObject.getString("event_locations_array"));
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject points = jsonArray.getJSONObject(i);
// 2 - the fields as double
double lat = points.getDouble("latitude");
double lang = points.getDouble("longitude");
}
setTextView();
} catch (JSONException e) {
e.printStackTrace();
}
}
Detailed solution
There are two errors:
The event_locations_array : "[[{"latitude":37.58728984572849].." contains a string. For the value that it's contains I think it must be generated as array (without the initial and final ")
After fix the first problem, you are trying to extract as object the properties latitude and longitude, but they are attributes. So change in your code:
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject points = jsonArray.getJSONObject(i);
JSONObject lat = points.getJSONObject("latitude");
JSONObject lang = points.getJSONObject("longitude");
}
With
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject points = jsonArray.getJSONObject(i);
double lat = points.getDouble("latitude");
double lang = points.getDouble("longitude");
}
To get Values of event_locations_array use following code:
JSONArray jsonArray = jsonResponse.getJSONArray("event_locations_array");
for (int i=0; i<jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String latitude = jsonObject.getString("latitude");
String longitude = jsonObject.getString("longitude");
}
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]);;
}
I am trying to connect my app using json but when I run my app it gets crashed. I think the problem is in the following code:
protected void onPostExecute(ArrayList result)
{
if (result == null)
{
Toast.makeText(MainActivity.this, "Failed to download Movies", Toast.LENGTH_LONG).show();
return;
}
JSONObject jsono = null;
// gridView gv = (GridView)findViewById(R.id.main_gridview);
ArrayList<Movie> l = new ArrayList<>();
try
{
jsono = new JSONObject((java.util.Map) result);
JSONArray jarray = jsono.getJSONArray("result");
for (int i = 0; i < jarray.length(); i++)
{
JSONObject object = jarray.getJSONObject(i);
String posterPath = object.getString("poster_path");
String title = object.getString("original_title");
String id = object.getString("id");
Movie m = new Movie(id, title, posterPath);
l.add(m);
}
}
catch (JSONException e)
{
e.printStackTrace();
}
MainAdapter adapter = new MainAdapter(MainActivity.this, result);
}
Someone kindly help me.
jsono = new JSONObject((java.util.Map) result);
Cast ArrayList to Map?
I think that you should read more basic knowledge about casting types in java, Maps, ArrayList and JSON.
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());
}
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());
}
}