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

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

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

Json array and object Parsing

Below is my JSON. I need to parse the news_title in the "newsdetail" from the category list object. What is the correct way to parse this data? please help me.
{"categorylist":[{"process":"news","ncid":"1"","newsdetail":[{"newsid":"604","category":"1","category_title":"","news_title":"just"},{"newsid":"606","category":"1","category_title":"","news_title":"fg"}]},{"process":"news","ncid":"2","newsdetail":[{"newsid":"477","category":"2","category_title":"","news_title":"way},{"newsid":"478","category":"1","category_title":"","news_title":"k"}]}
{"categorylist":[{"process":"news","ncid":"1"" // cannot be double quotes come here.
,"newsdetail":[{"newsid":"604","category":"1","category_title":"","news_title":"just"},{"newsid":"606","category":"1","category_title":"","news_title":"fg"}]},{"process":"news","ncid":"2","newsdetail":[{"newsid":"477","category":"2","category_title":"","news_title":"way},{"newsid":"478","category":"1","category_title":"","news_title":"k"}]}
you can use below parsor.. but your string data has some issue
try {
JSONObject jsonObject = new JSONObject(data);
JSONArray category_list = jsonObject.getJSONArray("category_list");
for (int i = 0; i < category_list.length() ; i++) {
// here you get news title for each news
String newsTitle = category_list.getJSONObject(i).getString("news_title");
}
}catch (JSONException e){
}

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

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

How stop a for loop when parsing a JSONArray for nameless JSONObject?

I want to parse a JSONArray that contains JSONObjects that have no names and whose (index int) positions within the array changes every week or so. I have attempted to parse a particular Object by it's attributes, but my parser only returns the last Object in the array.
How can i stop my loop when it reaches the object i want to parse and determine the int index of the object for further parsing.
try {
JSONArray jArray = JSONthing.getJSONfromURL("http://something.com");
String attributeiwant = "abc";
for (int i = 0; i < jArray.length(); i++) {
JSONObject alpha = jArray.getJSONObject(i);
String attributeparsed = alpha.getString("widget");
if (attributeparsed == attributeiwant) {
//determine int index of object, so i can parse other attributes
//from same object
}
}
} catch (Exception e) {
Log.e("log_tag", "Error parsing data "+ e.toString());
}
use String.equals for comparing Strings instead of ==
try {
JSONArray jArray = JSONthing.getJSONfromURL("http://something.com");
String attributeiwant = "abc";
for (int i = 0; i < jArray.length(); i++) {
JSONObject alpha = jArray.getJSONObject(i);
String attributeparsed = alpha.getString("widget");
if (attributeparsed.equals(attributeiwant)) {
//determine int index of object, so i can parse other attributes
//from same object
// Get data from JsonObject
break;
}
}
} catch (Exception e) {
Log.e("log_tag", "Error parsing data "+ e.toString());
}
use break; statement to break the loop, change your code to following:
int i = 0;
try {
JSONArray jArray = JSONthing.getJSONfromURL("http://something.com");
String attributeiwant = "abc";
for (; i < jArray.length(); i++) {
JSONObject alpha = jArray.getJSONObject(i);
String attributeparsed = alpha.getString("widget");
if (attributeparsed.equals(attributeiwant)) {
//determine int index of object, so i can parse other attributes
//from same object
break;
}
}
} catch (Exception e) {
Log.e("log_tag", "Error parsing data "+ e.toString());
}
if(i<jArray.length())
{
//item found, use i as index of object.
}
else
//item not found.

Categories

Resources