Get Data From Nested Array JSON Without Name Android - android

I'm trying to get the value of elevations from JSON in android but in the log nothing is shown. This JSON is a nested array, I'm still new toth parsing JSON in android.
This is what the JSON looks like :
This is my code :
try {
JSONObject responseObject = new JSONObject(result);
JSONArray elev = responseObject.getJSONArray("resourceSets");
JSONArray el = elev.getJSONObject(1).getJSONArray("elevations");
for(int i=0; i<=el.length();i++){
Log.d("EL",el.toString());
}
}
catch (Exception e){
e.printStackTrace();
}

try like below: (problem in your code is you are getting "elevations" directly without getting "resources" array)
try {
JSONObject responseObject = new JSONObject(result);
JSONArray elev = responseObject.getJSONArray("resourceSets");
JSONArray el_resources = elev.getJSONObject(0).getJSONArray("resources");
JSONArray el = el_resources.getJSONObject(0).getJSONArray("elevations");
for(int i=0; i<=el.length();i++){
Log.d("EL", el[i].toString()); // also get index from array then print it
}
}
catch (Exception e){
e.printStackTrace();
}

Related

json Parsing trouble in android

I get a problem when I parse this text as JSON. First, I created jsonobject from an URL. I can't show data when debugging, can anyone help me?
JSON:
[
{
"Tarih":"21.12.2015",
"Imsak":"05:51",
"Gunes":"07:22",
"Ogle":"12:18",
"Ikindi":"14:39",
"Aksam":"17:02",
"Yatsi":"18:26",
"Kible":"09:41"
}
]
I tried this code to solve it, but the JSON wasn't correctly parsed:
Java Code:
jsonobject = JSONfunctions.getJSONfromURL("http://namazvakitleri.ahmeti.net/index.php?islem=getSehirList&ulke_id=2");
try {
// Locate the NodeList name
jsonarray = jsonobject.getJSONArray("d");
for (int i = 0; i < jsonarray.length(); i++) {
jsonobject = jsonarray.getJSONObject(i);
WorldPopulation worldpop = new WorldPopulation();
worldpop.setCountry(jsonobject.optString("SehirId"));
worldpop.setPopulation(jsonobject.optString("population"));
world.add(worldpop);
// Populate spinner with country names
worldlist.add(jsonobject.optString("SehirAdi"));
}
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
'[' indicates a JsonArray whereas '{' indicates a JsonObject. You have assigned the result to the JsonObject. Instead of that assign it to JsonArray.
Also I don't see any key as "d" in you response.
Try this :
jsonarray = JSONfunctions
.getJSONfromURL("http://namazvakitleri.ahmeti.net/index.php?islem=getSehirList&ulke_id=2");
try {
for (int i = 0; i < jsonarray.length(); i++) {
jsonobject = jsonarray.getJSONObject(i);
WorldPopulation worldpop = new WorldPopulation();
worldpop.setCountry(jsonobject.optString("SehirId"));
worldpop.setPopulation(jsonobject.optString("population"));
world.add(worldpop);
// Populate spinner with country names
worldlist.add(jsonobject.optString("SehirAdi"));
}
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
But again please note your response does not contain this keys 'SehirId', 'population' and 'SehirAdi'
Your response is JsonArray not a JsonObject.
Now you have two ways to solve this problem.
change your getJSONfromURL() to return JsonArray
change response from server to return JsonObject instead of JsonArray
after doing above changes you must need to parse it according to your response.
Note : You have catch block available, so please try to check error in logcat and search on google related to that error.
try this solution :
try {
JSONArray jsonArray = new JSONArray("Your Response");
JSONObject jsonObject = (JSONObject) jsonArray.get(0);
Iterator keyNames = jsonObject.keys();
while (keyNames.hasNext()) {
String keyName = (String) keyNames.next();
String keyValue = jsonObject.getString(keyName);
}
} catch (Exception e) {
e.printStackTrace();
}

Create Jsonstring - Android

Hi i want to create json string like
{"id":"12345","option-ids":["100"]}
i've tried like below
JSONObject object = new JSONObject();
try {
object.put("id","12314");
JsonArray jsonArray = new JsonArray();
jsonArray......
object.put("option-ids",""+jsonArray);
} catch (JSONException e) {
e.printStackTrace();
}
but i struck on create json array withou object name.
// First - create the json Object
JSONObject object = new JSONObject();
try {
// Add the id to the json
object.put("id", "12314");
// Create a json array
JSONArray jsonArray = new JSONArray();
// Put the values you want
jsonArray.put("1");
jsonArray.put("2");
object.put("option-ids",jsonArray.toString());
} catch (JSONException e) {
// Handle impossible error
e.printStackTrace();
}
To insert String in JSONArray,use put() method of JSONArray.
try below code.
JSONObject object = new JSONObject();
try {
object.put("id","12345");
JSONArray jsonArray = new JSONArray();
jsonArray.put("100"); //add here
object.put("option-ids",jsonArray.toString());
} catch (JSONException e) {
e.printStackTrace();
}
You should use JSONArray (from org.json) instead of JsonArray(from com.google.gson)

Json in Android not working as it should

I have a problem with Json in android. In 4+ it works like a charm but in 2.2 it fails. I'm really stuck here.
I get error I get error: java.lang.ClassCastException: java.lang.String
In my server I parse array as:
[{"PRODUCT":
{"product_id":"1",
"name":"name1"}},
{"PRODUCT":
{"product_id":"2",
"name":"name2"}},
{"PRODUCT":
{"product_id":"3",
"name":"name3"}},
{"USER":{"user_id":"1"}
}]
in android app i use code as:
public void buildData(String jsonString, String code) {
mProduct = new HashMap<Integer, Product>();
try {
**here fails -> JSONArray array = (JSONArray) new JSONTokener(jsonString).nextValue();
// Object object = new JSONTokener(jsonString).nextValue();
// object = (object instanceof JSONArray) ? (JSONArray)object : (JSONObject)object ;
// JSONObject obj = (JSONObject) new JSONTokener(jsonString).nextValue();
for(int i = 0; i < array.length(); i++){
JSONObject json = array.getJSONObject(i);
if(json.has(JSON_PRODUCT)){
buildProduct(json.getString(JSON_PRODUCT), code);
}
else if(json.has(JSON_NAME)){
buildUser(json.getString(JSON_NAME));
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I'm not sure if the array is in the right form? If anyone can help me please.
I believe you should change the line to the following:
JSONArray array = new JSONArray(jsonString);
Then you can loop through it.

how do i parse a dynamic JSONArray by JSONObject attribute with Handler?

I want to parse this object from a JSON Array:
{..."avg": 8.492619161922457352960767294, "symbol": "mtgoxUSD", "low": 8.391000000000}
The JSONArray is dynamic, so sometimes it is the 73rd, 74th, or 75th object in the array and none of the objects in the array have names. I am currently using this code to parse it. It works fine when my particular object is in the 75th position, but crashes when it is not.
try {
JSONArray json = JSONfunctions2.getJSONfromURL("http://bitcoincharts.com/t/markets.json");
JSONObject forex = json.getJSONObject(75);
String btc = forex.getString("avg");
currencyBTC = Double.parseDouble(btc);
}catch(JSONException e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}
is it possible for me to identify the object by it's attributes, since the objects in the array have no names? How can i resolve this issue? Thank you in advance.
Edit:
This somewhat works, but only returns the values from the last object in the array. How do I handle this so that i can parse my particular object, and not just the last one? ...
try {
JSONArray jArray = JSONfunctions2.getJSONfromURL("http://bitcoincharts.com/t/markets.json");
String symbol = "mtgoxUSD";
for (int i = 0; i < jArray.length(); i++) {
JSONObject forex = jArray.getJSONObject(i);
String mtgoxUSD = forex.getString("symbol");
if (mtgoxUSD == symbol) {
String btc = forex.getString("avg");
double currencyBTC = Double.parseDouble(btc);
}
}
} catch (Exception e) {
Log.e("log_tag", "Error parsing data "+ e.toString());
}
This the way that I parse the JSON in an android application :
String s = client.getBaseURI("http://bitcoincharts.com/t/markets.json"); // Json format
JSONArray array = new JSONArray(s);
JSONObject obj;
for (int i = 0; i < array.length(); i++) {
obj = (JSONObject) array.get(i);
double average =Double.parsedouble(obj.get("avg").toString()));
String symbol = obj.get("symbol").toString();
double low = Double.parsedouble(obj.get("low").toString());
}
I also want to add that I use HTTP Client library to fetch the data from server. To have more information about how to use HTTP Client, check my answer in this link: HTTP Client
Is the "75" going to be dynamic as well? Meaning, will the number changed based on user input? If so, you'll need to have a handle for that but anyway, just use a for loop, something like the following:
try {
JSONArray jArray = JSONfunctions2.getJSONfromURL("http://bitcoincharts.com/t/markets.json");
String symbol = "mtgoxUSD";
for (int i = 0; i < jArray.length(); i++) {
JSONObject forex = jArray.getJSONObject(i);
String mtgoxUSD = forex.getString("symbol");
if (mtgoxUSD == symbol) {
String btc = forex.getString("avg");
double currencyBTC = Double.parseDouble(btc);
}
}
} catch (Exception e) {
Log.e("log_tag", "Error parsing data "+ e.toString());
}

android json to listview

I working with android and JSON. I came so far, but I can's set the ID in the arraylist.The error will be in "json_data.getInt("ID")"
Can sombody help me
public void klussenlijst()
{
ArrayList<String> results = new ArrayList<String>();
JSONObject json_data;
mysql client = new mysql("http://www.****************/klussen.php?actie=klussen");
try {
client.Execute(RequestMethod.POST);
} catch (Exception e) {
e.printStackTrace();
}
String response = client.getResponse();
try{;
JSONArray jArray = new JSONArray(response);
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
results.add(json_data.getInt("ID"),(String) json_data.get("titel").toString());
}
filllist();
}
catch(JSONException e){
e.printStackTrace();
}
}
Not sure about your mysql() method and the huge lack of error handling, but are you sure that your project has allowed for INTERNET permissions in your AndroidManifest.xml file? Sounds to me like your getInt is not an int.

Categories

Resources