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();
}
Related
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();
}
How to read the images and its corresponding positions
"images": [
[
{
"images_url": "http://provenlogic.info/tinder_web/public/uploads/e9275d47cf5efd929794caafc50e957982c47582.jpg",
"position": "1"
},
{
"images_url": "http://provenlogic.info/tinder_web/public/uploads/c374561da8583a77b4d21ee4b06f30d1a3fac4bb.jpg",
"position": "3"
}
]
]
try {
JSONArray jsonArray = rootObject.getJSONArray("images");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String imageUrl=jsonObject.getString("images_url");
String position=jsonObject.getString("position");
}
} catch (Exception e) {
e.printStackTrace();
}
Happy Codding!!!
A JSON Object starts with a { and ends with a } while a JSON Array starts with a [ and ends with a ].
JSONArray jArray = json.getJSONArray("images").get;
for(int i = 0; i < jArray.length;i++)
{
JSONObject jObj = jsonArray.getJSONObject(i);
String imageUrl = jObj.getString("images_url");
String position = jObj.getString("position");
}
You will need to wrap the whole JSON Handling inside a try/catch block. You might want to try http://jsonlint.com/, an online json validator and https://jsonformatter.curiousconcept.com/, an online json formatter to understand easily!
Cheers!
First of all get the JsonArray by using array name "images"
and get each Json object .
try {
JSONArray jsonArray = new JSONArray("result");
for(int i=0;i<jsonArray.length();i++){
JSONArray jsonArray1=jsonArray.getJSONArray(i);
for(int j=0;j<jsonArray1.length();j++){
JSONObject jsonObject=jsonArray1.getJSONObject(j);
String imageurl=jsonObject.getString("images_url");
String position=jsonObject.getString("position");
}
}
}catch (Exception e){
e.printStackTrace();
}
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").
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.
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());
}