how to convert a string that contain array element into JSONArray - android

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.

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.

Json move to next item

I have a dynamic JSON string that looks like this:
{"_id":"7","food_name":"Fiber Balance"},{"_id":"8","food_name":"Sport +"}
I am able to get the first name, but not the second one. This is my code for getting the first (Fiber Balance):
// Dynamic text
TextView textViewDynamicText = (TextView)getActivity().findViewById(R.id.textViewDynamicText);
String stringJSON = textViewDynamicText.getText().toString();
String stringFoodname = "";
try {
JSONObject jsonObject = new JSONObject(stringJSON);
Iterator<String> iter = jsonObject.keys();
while (iter.hasNext()) {
String key = iter.next();
try {
stringFoodname = jsonObject.getString("food_name");
Toast.makeText(getContext(), stringFoodname, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
// Something went wrong!
}
}
} catch (org.json.JSONException e) {
// Something went wrong!
}
How can I go to the next item in the json string?
If you have multiple data than you need to use Array,if you want to get all data from your json use below trick,
String json = "{\"_id\":\"7\",\"food_name\":\"Fiber Balance\"},{\"_id\":\"8\",\"food_name\":\"Sport +\"}";
json = "[" + json + "]";
try {
JSONArray array = new JSONArray(json);
for (int i = 0; i < array.length(); i++) {
JSONObject object = array.getJSONObject(i);
String foodName = object.getString("food_name");
Log.e("FoodName:", foodName);
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("error", "json", e);
}

Parsing a JSON file without arrays

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/

How to create JSONObject and JSON ARRAy from json string in android?

My String contains json
result=[{"USER_ID":83,"PROJECT_BY_DETAILS":"An adaptation of a nursery rhyme into a dramatic film"},{"USER_ID":88,"PROJECT_BY_DETAILS":"Test - over ye mountain blue "}]
How to create JSONOBject and JSONarray from this string
I used this code
JSONObject json =new JSONObject(result);
//Get the element that holds the earthquakes ( JSONArray )
JSONArray earthquakes = json.getJSONArray("");
i got error
Error parsing data org.json.JSONException: Value [{"USER_ID":83,"PRO
If it starts with [ its an array, try with:
JSONArray json =new JSONArray(result);
Difference between JSONObject and JSONArray
use this code for your JsonArray:
try {
JSONArray json = new JSONArray(YOUR_JSON_STRING);
for (int i = 0; i < json.length(); i++) {
JSONObject jsonDATA = json.getJSONObject(i);
String jsonid = jsonDATA.getInt("USER_ID");
String jsondetails = jsonDATA.getString("PROJECT_BY_DETAILS");
}
} catch (JSONException e) {
return null;
}
use Gson for you to do that.
That Json response is an array you know it because of the square brackets [].
Create a mapping object (a java class) with field USER_ID and PROJECT_BY_DETAILS.
public class yourClass(){
public String USER_ID;
public String PROJECT_BY_DETAILS;
}
Create a Type array like so.
final Type typeYourObject = new TypeToken>(){}.getType();
define your list private
List yourList;
Using Gson you will convert that array to a List like so
yourList = gson.fromJson(yourJson, typeYourObject);
with that list later you can do whatever you want. Also with Gson convert it back to JsonArray or create a customs JsonObject.
According to my understanding the JSON object looks like this,
{
"RESULT":[
{
"USER_ID":83,
"PROJECT_BY_DETAILS":"An adaptation of a nursery rhyme into a dramatic film"
},
{
"USER_ID":88,
"PROJECT_BY_DETAILS":"Test - over ye mountain blue "
}
]
}
You are converting this to a String and you wish to re-construct the JSON object. The decode function in the android-side would be this,
void jsonDecode(String jsonResponse)
{
try
{
JSONObject jsonRootObject = new JSONObject(jsonResponse);
JSONArray jData = jsonRootObject.getJSONArray("RESULT");
for(int i = 0; i < jData.length(); ++i)
{
JSONObject jObj = jData.getJSONObject(i);
String userID = jObj.optString("USER_ID");
String projectDetails = jObj.optString("PROJECT_BY_DETAILS");
Toast.makeText(context, userID + " -- " + projectDetails,0).show();
}
}
catch(JSONException e)
{
e.printStackTrace();
}
}

Categories

Resources