Parsing a JSON file without arrays - android

I am trying to parse this: https://s3.amazonaws.com/dolartoday/data.json for an Android app that shows the dollar to bolivar unofficial exchange rate.
I am using this tutorial: http://www.androidhive.info/2012/01/android-json-parsing-tutorial/, which I have used successfully before, however previous APIs I have used consisted of a JSON array with child objects. This one, however, has 12 JSON objects with strings. No square brackets to be seen.
The part (I think) I'm having trouble with is:
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("contacts");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString("id");
String name = c.getString("name");
String email = c.getString("email");
String address = c.getString("address");
String gender = c.getString("gender");
// Phone node is JSON Object
JSONObject phone = c.getJSONObject("phone");
String mobile = phone.getString("mobile");
String home = phone.getString("home");
String office = phone.getString("office");
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
}
I'm no expert, since I'm trying to learn programming on my own and I'm still very new. However, I have made some changes including getting rid of the ListView, and adapting the code to the new JSON.
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Object node
JSONObject c = jsonObj.getJSONObject("USD");
JSONObject d = jsonObj.getJSONObject("EUR");
String usdtrans = c.getString("dolartoday");
String usdreal = c.getString("efectivo_real");
String usddicom = c.getString("sicad2");
String eurtrans = d.getString("dolartoday");
String eurreal = d.getString("efectivo_real");
String eurdicom = d.getString("sicad2");
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
}
The code does not compile, and Android Studio detects an "unhandled exception: org.json.JSONException". What can I do to change this?
Any help would be appreciated. The rest of my code has other issues as well, but I think I can sort those out once I can get this one done.

While using org.json library classes, If the JSON response consists of square bracket "[" then we need to get that element as JSONArray else get the element as JSONObject.
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONObject antibloqueo = jsonObject.getJSONObject("_antibloqueo");
JSONObject labels = jsonObject.getJSONObject("_labels");
JSONObject timestamp = jsonObject.getJSONObject("_timestamp");
JSONObject USD = jsonObject.getJSONObject("USD");
JSONObject EUR = jsonObject.getJSONObject("EUR");
JSONObject COL = jsonObject.getJSONObject("COL");
JSONObject GOLD = jsonObject.getJSONObject("GOLD");
JSONObject USDVEF = jsonObject.getJSONObject("USDVEF");
JSONObject USDCOL = jsonObject.getJSONObject("USDCOL");
JSONObject EURUSD = jsonObject.getJSONObject("EURUSD");
JSONObject BCV = jsonObject.getJSONObject("BCV");
JSONObject MISC = jsonObject.getJSONObject("MISC");
//To get Values From antibloqueo
String mobile = antibloqueo.getString("mobile");
String video = antibloqueo.getString("video");
//To get Values From labels
String a = labels.getString("DOLARTODAY");
String a1 = labels.getString("a1");
} catch (JSONException e) {
Log.e("TAG", "Json parsing error: " + e.getMessage());
}
Note:
While working with smaller projects you can use org.json library as the JSON Convertor. For the bigger projects you have to use other libraries like Gson /Jackson
https://www.mkyong.com/java/how-do-convert-java-object-to-from-json-format-gson-api/

Related

Problem with using JSON when trying get more data like "fields"

I have this code to get all information from website, I did it very well and it works, but I got stuck when trying to get "fields" from the site
This is the site url:
http://content.guardianapis.com/search?order-by=newest&show-references=author&show-tags=contributor&q=technology&show-fields=thumbnail&api-key=test
Here is the code and how can I fix it
try {
JSONObject jsonRes = new JSONObject(response);
JSONObject jsonResults = jsonRes.getJSONObject("response");
JSONArray resultsArray = jsonResults.getJSONArray("results");
for (int i = 0; i < resultsArray.length(); i++) {
JSONObject oneResult = resultsArray.getJSONObject(i);
String url = oneResult.getString("webUrl");
String webTitle = oneResult.getString("webTitle");
String section = oneResult.getString("sectionName");
String date = oneResult.getString("webPublicationDate");
date = formatDate(date);
JSONArray fields = oneResult.getJSONArray("fields");
JSONArray fieldsArray=oneResult.getJSONArray("fields");
String imageThumbnail= null;
if(fields.length()>0){
imageThumbnail=fields.getJSONObject(0).getString("thumbnail");
}
resultOfNewsData.add(new News(webTitle url, date, section, imageThumbnail));
}
} catch (JSONException e) {
Log.e("FromLoader", "Err parsing response", e);
}
Because the fields object isn't an Array is a JSON object
"fields":{"thumbnail":"https://media.guim.co.uk/fa5ae6ca7c78fdfc4ac0fe4212562e6daf4dfb3d/0_265_4032_2419/500.jpg"}
An array object should contain [ JSON1, JSON2, JSON3 ]
In your case this
JSONArray fields = oneResult.getJSONArray("fields");
becomes this
JSONObject fields = oneResult.getJSONObject("fields");
And I don't understand why are you getting the same data twice - fields and fieldsArray

How can i get the value that are inside several arrays when getting json data? [duplicate]

This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 4 years ago.
I'm making an android app to control my AC, in my app i would like to know the temperature outside. I have an json link to the local weather forecast provider and it have the temperature value I'm looking for.
Link to JSON (https://opendata-download-metfcst.smhi.se/api/category/pmp3g/version/2/geotype/point/lon/16.158/lat/58.5812/data.json)
My problem is that I don't know how to get to the temperature value when it´s inside several arrays. The object I'm looking for is inside "timeSeries" -> "parameters" -> and the name is "t" and it is that "value" I want (it´s the temperature in Celsius).
I have tried several ways of fix it but obvious I'm not there :). I insert a part of my code so you can see what I'm trying.
#Override
public void onResponse(Call call, Response response) throws IOException {
String forecastData;
try {
String jsonData = response.body().string();
Log.v(TAG, jsonData);
if (response.isSuccessful()) {
forecastData = getCurrentDetails(jsonData);
}
} catch (IOException e) {
Log.e(TAG, "IO Exception caught: ", e);
} catch (JSONException e) {
Log.e(TAG, "JSON Exception caught:", e);
}
}
private String getCurrentDetails(String jsonData) throws JSONException {
JSONObject forecast = new JSONObject(jsonData);
JSONArray currently = forecast.getJSONArray("timeSeries");
String currentTemp = "";
return currentTemp;
}
});
It´s in the getCurrentDetails i want to get the temperature and then return it.
If you want to get the latest temperature from the json data
In getCurrentDetails() method:
JsonObject forecast = new JsonObject(jsonData);
JsonArray timeSeries = forecast.getJsonArray("timeSeries");
JsonObject current = timeSeries.getJsonObject(0);
JsonArray parameters = current.getJsonArray("parameters");
JsonObject firstParam = parameters.getJsonObject(parameters.length() - 1);
JsonArray values = firstParam.getJsonArray("values");
String tempValue = values.getString(0);
//You can now return the tempValue
If you want to get all temperatures in the jsonData
In getCurrentDetails() method:
JsonObject forecast = new JsonObject(jsonData);
JsonArray timeSeries = forecast.getJsonArray("timeSeries");
ArrayList<String> temps = new ArrayList<>();
for(int i=0; i < timeSeries.length(); i++){
JsonObject current = timeSeries.getJsonObject(i);
JsonArray parameters = current.getJsonArray("parameters");
JsonObject firstParam = parameters.getJsonObject(parameters.length() - 1);
JsonArray values = firstParam.getJsonArray("values");
String tempValue = values.getString(0);
temps.add(tempValue);
}
// You can now return the temps.
//NOTE that in this case, your
//getCurrentDetails() method should
//return ArrayList<String> not String.

parsing JSON string for an array in Java

I am writing an Android application that pulls JSON data from an SQL db.
In my Async Task class, I receive a JSON string from an HTTP request and I assign it to a JSONObject. This string contains various data, including an array of coordinates which I need. After that, I do obj.getJSONArray("coordinates"); As soon as I do that, my application throws an exception:
org.json.JSONObject cannot be converted to JSONArray in android
I am following this post's approach to solve my issues but with no luck:
org.json.JSONObject cannot be converted to JSONArray in android
I feel like I need to iterate over my JSON string until I see that array. I will post the string data below.
protected Void doInBackground(Void... voids) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(address);
//Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject obj = new JSONObject(jsonStr);
JSONArray deviceJsonArray = obj.getJSONArray("coordinates"); //ERROR OCCURS HERE!
// looping through All Devices
for (int i = 0; i < deviceJsonArray.length(); i++) {
JSONObject json = deviceJsonArray.getJSONObject(i);
//String DeviceID = c.getString("id");
// longitude = json.getDouble("longitude");
// latitude = json.getDouble("latitude");
Device device = new Device();
device.setName(receivedDeviceName);
//Adding the information to the array.
coordinatesArray.add(device);
}
//Log.e(TAG, "arraylist: " + coordinatesArray);
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
JSON string value:
{"data":{"type":"gps","total_distance":18,"coordinates":[{"latitude":49.169209,"longitude":-122.990952,"time":"12:02:38 AM"},{"latitude":49.16922,"longitude":-122.990959,"time":"2:42:33 PM"},{"latitude":49.1693,"longitude":-122.988098,"time":"5:16:33 PM"},{"latitude":49.170979,"longitude":-122.968239,"time":"5:18:33 PM"},{"latitude":49.174992,"longitude":-122.962502,"time":"5:20:33 PM"},{"latitude":49.17688,"longitude":-122.95768,"time":"5:22:33 PM"},{"latitude":49.182232,"longitude":-122.960297,"time":"5:24:33 PM"},{"latitude":49.18581,"longitude":-122.950813,"time":"5:26:33 PM"},{"latitude":49.188869,"longitude":-122.945969,"time":"5:28:33 PM"},{"latitude":49.197689,"longitude":-122.948502,"time":"5:30:33 PM"},{"latitude":49.20216,"longitude":-122.947418,"time":"5:32:33 PM"},{"latitude":49.2071,"longitude":-122.949593,"time":"5:34:33 PM"},{"latitude":49.213051,"longitude":-122.938522,"time":"5:36:33 PM"},{"latitude":49.215462,"longitude":-122.93399,"time":"5:38:33 PM"},{"latitude":49.216381,"longitude":-122.932297,"time":"5:40:33 PM"},{"latitude":49.218769,"longitude":-122.92791,"time":"5:42:33 PM"},{"latitude":49.221062,"longitude":-122.923653,"time":"5:44:33 PM"},{"latitude":49.227119,"longitude":-122.912392,"time":"5:46:33 PM"},{"latitude":49.234489,"longitude":-122.89872,"time":"5:48:33 PM"},{"latitude":49.235699,"longitude":-122.894608,"time":"5:50:33 PM"},{"latitude":49.241928,"longitude":-122.89257,"time":"5:52:33 PM"},{"latitude":49.241871,"longitude":-122.89016,"time":"6:02:33 PM"}]}}
Could someone see what I am doing wrong or recommend a fix please?
Try this instead:
JSONObject obj = new JSONObject(jsonStr);
JSONObject objData = obj.getJSONObject("data");
JSONArray deviceJsonArray = objData.getJSONArray("coordinates");
The "coordinates" JSONArray is one element deeper in your JSON structure

how to convert a string that contain array element into JSONArray

I've been experiencing some problems for quite some time trying to load a string that contains an array into a JSONArray.
i get the following string from a web-service which contains the movies array:
{"total":3,"movies":[],"links":{......}"}
i'm looking to convert this array into a JASONArray and show it using a list view.
i'm using the following code and it not working....
protected void onPostExecute(String result) {
Log.d(TAG, "result: " + result);
if (result==null || result.length()==0){
// no result:
return;
}
//clear the list
moviesList.clear();
try {
//turn the result into a JSON object
Log.d(TAG, "create responseObject: ");
JSONObject responseObject = new JSONObject(result);
Log.d(TAG, responseObject.toString());
// get the JSON array named "movies"
JSONArray resultsArray = responseObject.getJSONArray("movies");
Log.d(TAG, "JSONArray lenght: " + resultsArray.length());
// Iterate over the JSON array:
for (int i = 0; i < resultsArray.length(); i++) {
// the JSON object in position i
JSONObject movieObject = resultsArray.getJSONObject(i);
Log.d(TAG, "movieObject (from array) : " + movieObject.toString());
// get the primitive values in the object
String title = movieObject.getString("title");
String details = movieObject.getString("synopsis");
//put into the list:
Movie movie = new Movie(title, details, null,null);
//public Movie(String title, String details, String urlnet, String urldevice) {
moviesList.add(movie);
}
} catch (JSONException e) {
e.printStackTrace();
}
//refresh listView:
adapter.notifyDataSetChanged();
}
I was hoping a post here would help me solve the problem.
Change this:
JSONObject responseObject = new JSONObject(result);
to this:
JSONObject responseObject = (JSONObject) JSONValue.parse(result);
and then you can get your JSONArray.

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

Categories

Resources