This question already has answers here:
How do I parse JSON in Android? [duplicate]
(3 answers)
Closed 5 years ago.
My json is like this i want to parse newsitems to get tittle,url,contents,feelabel,url and feedlabel
{
"appnews": {
"appid": 466560,
"newsitems": [
{
"gid": "2284879949551103234",
"title": "These are the top 100 Steam games of 2017",
"url": "http://store.steampowered.com/news/externalpost/rps/2284879949551103234",
"is_external_url": true,
"author": "contact#rockpapershotgun.com (Alec Meer)",
"contents": "Another year over, a new one just begun, which means, impossibly, <em>even more games.</em> But what about last year? Which were the games that most people were buying and, more importantly, playing? As is now something of a tradition, Valve have let slip a big ol’ breakdown of the most successful titl...",
"feedlabel": "Rock, Paper, Shotgun",
"date": 1514919601,
"feedname": "rps",
"feed_type": 0,
"appid": 550
},
{
"gid": "2284879949546841782",
"title": "ShiroGames - Bye bye 2017 and WELCOME 2018 !!!",
"url": "http://store.steampowered.com/news/externalpost/steam_community_announcements/2284879949546841782",
"is_external_url": true,
"author": "Lord_brioche",
"contents": "Hello Northgardians, As the end of 2017 is upon us, we wanted to share with you a few thoughts. What a year! At the beginning of 2017, Northgard was about to start its 6-months Early Access period. At the time, the game was supposed to be a fun, solo strategy game with 4 clans and ShiroGames was onl...",
"feedlabel": "Community Announcements",
"date": 1514818282,
"feedname": "steam_community_announcements",
"feed_type": 1,
"appid": 466560
},
{
"gid": "2284879949521363459",
"title": "Best PC games of 2017",
"url": "http://store.steampowered.com/news/externalpost/rps/2284879949521363459",
"is_external_url": true,
"author": "contact#rockpapershotgun.com (RPS)",
"contents": "The calendar’s doors have been opened and the games inside have been eaten. But fear not, latecomer – we’ve reconstructed the list in this single post for easy re-consumption. Click on to discover the best games of 2017. (more…) ",
"feedlabel": "Rock, Paper, Shotgun",
"date": 1514206814,
"feedname": "rps",
"feed_type": 0,
"appid": 240720
}
]
,
"count": 57
}
}
Json parsing code is like this
#Override
protected Void doInBackground(Void... arg0) {
News news = new News();
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String url = "http://api.steampowered.com/ISteamNews/GetNewsForApp/v0002/?appid=466560&count=3&maxlength=300&format=json";
String jsonStr = sh.makeServiceCall(url);
;
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray contacts = jsonObj.getJSONArray("appnews");
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
news.setTittle( c.getString("title"));
news.setContent(c.getString("content"));
news.setDate(c.getString("date"));
news.setFeed(c.getString("feedlabel"));
news.setUrl(c.getString("url"));
newsList.add(news);
}
} catch (final JSONException e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
}
});
}
} else {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server",
Toast.LENGTH_LONG).show();
}
});
}
return null;
}
I got error like this i want to parse newsitems to get tittle,url,contents,feelabel,url and feedlabel i used this tutorial https://www.tutorialspoint.com/android/android_json_parser.htm
org.json.JSONException: Value {"appid":466560,"newsitems":[{"gid":"2284879949551103234","title":"These are the top 100 Steam games of 2017","url":"http:\/\/store.steampowered.com\/news\/externalpost\/rps\/2284879949551103234","is_external_url":true,"author":"contact#rockpapershotgun.com (Alec Meer)","contents":"Another year over, a new one just begun, which means, impossibly, <em>even more games.<\/em> But what about last year? Which were the games that most people were buying and, more importantly, playing? As is now something of a tradition, Valve have let slip a big ol’ breakdown of the most successful titl...","feedlabel":"Rock, Paper, Shotgun","date":1514919601,"feedname":"rps","feed_type":0,"appid":550},{"gid":"2284879949546841782","title":"ShiroGames - Bye bye 2017 and WELCOME 2018 !!!","url":"http:\/\/store.steampowered.com\/news\/externalpost\/steam_community_announcements\/2284879949546841782","is_external_url":true,"author":"Lord_brioche","contents":"Hello Northgardians, As the end of 2017 is upon us, we wanted to share with you a few thoughts. What a year! At the beginning of 2017, Northgard was about to start its 6-months Early Access period. At the time, the game was supposed to be a fun, solo strategy game with 4 clans and ShiroGames was onl...","feedlabel":"Community Announcements","date":1514818282,"feedname":"steam_community_announcements","feed_type":1,"appid":466560},{"gid":"2284879949521363459","title":"Best PC games of 2017","url":"http:\/\/store.steampowered.com\/news\/externalpost\/rps\/2284879949521363459","is_external_url":true,"author":"contact#rockpapershotgun.com (RPS)","contents":"The calendar’s doors have been opened and the games inside have been eaten. But fear not, latecomer – we’ve reconstructed the list in this single post for easy re-consumption. Click on to discover the best games of 2017. <a href=\"https:\/\/www.rockpapershotgun.com\/2017\/12\/25\/best-pc-games-of-2017\/#more-503951\" class=\"more-link\">(more…)<\/a> ","feedlabel":"Rock, Paper, Shotgun","date":1514206814,"feedname":"rps","feed_type":0,"appid":240720}],"count":57} at appnews of type org.json.JSONObject cannot be converted to JSONArray
appnews is JSONObject so
// fetch appnews jsonobject
JSONArray news= jsonObj.getJSONObject("appnews");
// fetch the news items jsonarray which actually contains your data
JSONArray contacts = news.getJSONArray("newsitems");
There is a typo and apparently, there's already a news object so
JSONArray appNews= jsonObj.getJSONObject("appnews");
JSONArray contacts = appNews.getJSONArray("newsitems");
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
news.setTittle( c.getString("title"));
news.setContent(c.getString("contents"));
news.setDate(c.getString("date"));
news.setFeed(c.getString("feedlabel"));
news.setUrl(c.getString("url"));
newsList.add(news);
}
Try This
try
{
JSONObject jsonObj = new JSONObject(jsonStr);
JSONObject jsonObjAppnews = jsonObj.getString("appnews");
JSONArray contacts = jsonObjAppnews.getJSONArray("newsitems");
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
news.setTittle( c.getString("title"));
news.setContent(c.getString("contents"));
news.setDate(c.getString("date"));
news.setFeed(c.getString("feedlabel"));
news.setUrl(c.getString("url"));
newsList.add(news);
}
}
catch (final JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
Related
I have held off asking for help on this one, until I have spent over a week reading every post and google and stack overflow question i can find on this error, and still nothing, so here I am. I am retrieving a list of posts from my website using Android Studio, via the WordPress API. The url is returning the correct data, but here might be an issue with the data, (it's from a Weaver Xtreme Pro Theme), but I cannot find it, so in case it is, I have included it.
the url response is, "
...Response from url: [{"id":113,"title":{"rendered":"New England\u2019s Small, Diverse Farms are a Boon for Shrubland Birds"}},{"id":110,"title":{"rendered":"Cattle raisers oppose changes to Federal water regulation"}},{"id":108,"title":{"rendered":"FCA board approves bookletter on governance of wholesale funding and related practices"}},{"id":106,"title":{"rendered":"Texas cattle raisers fight to protect water rights in Texas Supreme Court briefing"}},{"id":103,"title":{"rendered":"Episode 11 \u2013 Parlez-vous fran\u00e7ais?"}},{"id":101,"title":{"rendered":"Episode 10 \u2013 Did Spanish Colonization have a chance?"}},{"id":96,"title":{"rendered":"Episode 9 – The French make a try in Texas"}},{"id":93,"title":{"rendered":"Episode 8- The Spanish Presidios and tensions begin rising between cultures"}},{"id":90,"title":{"rendered":"Episode 7- The Spanish Missions"}},{"id":87,"title":{"rendered":"Episode 6 \u2013 A clash of cultures between the Spanish and the local peoples"}}]
The code I am using to parse it is here.
enter code here #Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String url = "https://(my website)/wp-json/wp/v2/posts?_fields[]=title&_fields[]=id";
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null){
try {
JSONObject parent = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray Stories = parent.getJSONArray("storyList");
// looping through All stories (i.e. the posts)
for (int i = 0; i < Stories.length(); i++) {
JSONObject s = Stories.getJSONObject(i);
story_title = s.getString("title");
story_id = s.getString("id");
// tmp hash map for single contact
HashMap<String, String> story = new HashMap<>();
// adding each child node to HashMap key => value
story.put("storytitle", story_title);
story.put("storyid", story_id);
// adding the story info to the story list
storyList.add(story);
}
} 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;
}
Logcat is showing this error on the exception:
...Json parsing error: Value [{"id":113,"title":{"rendered":"New England’s Small, Diverse Farms are a Boon for Shrubland Birds"}},{"id":110,"title":{"rendered":"Cattle raisers oppose changes to Federal water regulation"}},{"id":108,"title":{"rendered":"FCA board approves bookletter on governance of wholesale funding and related practices"}},{"id":106,"title":{"rendered":"Texas cattle raisers fight to protect water rights in Texas Supreme Court briefing"}},{"id":103,"title":{"rendered":"Episode 11 – Parlez-vous français?"}},{"id":101,"title":{"rendered":"Episode 10 – Did Spanish Colonization have a chance?"}},{"id":96,"title":{"rendered":"Episode 9 – The French make a try in Texas"}},{"id":93,"title":{"rendered":"Episode 8- The Spanish Presidios and tensions begin rising between cultures"}},{"id":90,"title":{"rendered":"Episode 7- The Spanish Missions"}},{"id":87,"title":{"rendered":"Episode 6 – A clash of cultures between the Spanish and the local peoples"}}] of type org.json.JSONArray cannot be converted to JSONObject
I realize this is similar to other posts, but for the life of me after reading them and trying to implement some of the answers, I still getting the exception error. I may have overlooked an exact answer that deals with this type of situation, so any help would be appreciated
TIA
The mistake is that your json is an array but you try to parse it as an object.
Change this code :
JSONObject parent = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray Stories = parent.getJSONArray("storyList");
.
by
JSONArray Stories = new JSONArray(jsonStr);
I have been attempting to retrieve information from an online JSON Source using a URL. I initially got the information parsed to a TextView in Android, however I got ALL Information from the JSON. Below is a screenshot of what I am referring to.
Text View Showing All Data In Json
Essentially, What I want is to just show the Location, so in the above example, Oslo, in Norway in one Textview, then in another show the Current Moon Phase for that location, so - using the above example again, Waxing Crescent.
This is the JSON I am using.
{
"version": 2,
"locations": [{
"id": "187",
"geo": {
"name": "Oslo",
"country": {
"id": "no",
"name": "Norway"
},
"latitude": 59.913,
"longitude": 10.740
},
"astronomy": {
"objects": [{
"name": "moon",
"days": [{
"date": "2018-09-13",
"events": [],
"moonphase": "waxingcrescent"
}]
}]
}
}]
}
To parse the JSON to the Textview showing all the data I used the following.
JSONObject jo = new JSONObject(data);
JSONArray locations = jo.getJSONArray("locations");
for (int i = 0; i < locations.length(); ++i) {
JSONObject loc = locations.getJSONObject(0);
JSONObject geo = loc.getJSONObject("geo");
JSONObject country = geo.getJSONObject("country");
JSONObject astronomy = loc.getJSONObject("astronomy");
JSONObject objects = astronomy.getJSONArray("objects").getJSONObject(0);
JSONObject day = objects.getJSONArray("days").getJSONObject(0);
StringBuilder result = new StringBuilder();
String singleParsed = "Moon: "+ astronomy.getString("moonphase");
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#RequiresApi(api = Build.VERSION_CODES.CUPCAKE)
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
MainActivity.fetcheddata.setText(this.data);
}
NOTE: A String is created in the For Loop, Called "Single Parsed", This is what I want to put on the screen, however - once I call that variable, nothing shows on the screen. It only shows when using:
MainActivity.fetcheddata.setText(this.data);
But Not with the following, I do actually receive an error saying "Cannot Resolve Symbol, singleParsed as well.
MainActivity.fetcheddata.setText(this.singleParsed);
After some research and previous questions on Stack, I believe GSON is the way to go to do what I wish, however I have no idea where to start, or how to do the task using GSON.
All help is appreciated.
JSON Information from URL through GSON
Simple answer - Look at using Retrofit, and find a tutorial on it, as well as Gson
However
You don't need Gson to fix your problem, and I suggest fixing the problem at hand rather than going down an unnecessary path.
First, singleParsed is a local variable within a loop. Therefore, this.singleParsed doesn't exist. Or if it does, you never set it.
Secondly, let's assume you only have one location, so you don't need a loop. Similar to how you accessed the other JSON arrays, just get the first array item.
Finally, you'll need to understand how AsyncTask works, but my general recommended solution is at How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?
But, for this purpose, here is a simple example with AsyncTask<String, Void, String>
// protected String doInBackground(String... url) { // I assume you have this ??
// String data = parseJsonFrom(url[0]);
String singleParsed = "(none)";
try {
JSONObject jo = new JSONObject(data);
JSONObject firstLocationAstronomy = jo
.getJSONArray("locations").getJSONObject(0)
.getJSONObject("astronomy");
JSONObject firstDay = firstLocationAstronomy
.getJSONArray("objects").getJSONObject(0)
.getJSONArray("days").getJSONObject(0);
singleParsed = firstDay.getString("moonphase");
} catch (Exception e) { // TODO: catch a JSONParseException
}
return singleParsed; // This is returned to onPostExecute, don't store a variable elsewhere
}
Then in the MainActivity, wherever you make this task, and set the text
new MoonPhaseTask() {
#Override
protected void onPostExecute(String moonPhase) {
MainActivity.this.textView.setText("Phase: " + moonPhase);
}
}.execute("some url");
What I want is to just show the Location, so in the above example, Oslo, in Norway in one Textview, then in another show the Current Moon Phase for that location
You can change the AsyncTask to return you the entire JSONObject to the onPostExecute, and parse the JSON there if you really wanted. Just the networking pieces need to be off the UI thread... parsing is not computationally expensive.
I have a JSONString that came back successfully and I want to convert it into a JSONArray where I can parse the bits. The string came back successfully but when I try to log the "title" within each movie's object inside the "results" array, it's not coming up.
public List<MovieItem> fetchItems() {
List<MovieItem> items = new ArrayList<>();
try {
String url = Uri.parse("https://api.themoviedb.org/3/movie/popular")
.buildUpon()
.appendQueryParameter("api_key", API_KEY)
.build().toString();
String jsonString = getUrlString(url);
Log.i(TAG, "Received JSON: " + jsonString);
JSONObject jsonBody = new JSONObject(jsonString);
JSONArray photoJsonArray = jsonBody.getJSONArray("results");
for(int i = 0; i < photoJsonArray.length(); i++){
JSONObject jsonPart = photoJsonArray.getJSONObject(i);
Log.i("title", jsonPart.getString("title"));
}
} catch (IOException ioe) {
Log.e(TAG, "Failed to fetch items", ioe);
} catch (JSONException je) {
Log.e(TAG, "Failed to parse", je);
}
return items;
}
-
02-03 13:34:43.236 4728-4746/? I/MovieFetchr: Received JSON: {
"page":1,
"results":[
{
"poster_path":"\/oXUWEc5i3wYyFnL1Ycu8ppxxPvs.jpg",
"adult":false,
"overview":"In the 1820s, a frontiersman, Hugh Glass, sets out on a path of vengeance against those who left him for dead after a bear mauling.",
"release_date":"2015-12-25",
"genre_ids":[37,18,12,53],
"id":281957,
"original_title":"The Revenant",
"original_language":"en",
"title":"The Revenant",
"backdrop_path":"\/uETWtwsE1QjfoFqRQqFLnSjppPA.jpg",
"popularity":42.096309,
"vote_count":1079,
"video":false,
"vote_average":7.36
},
{
"poster_path":"\/kqjL17yufvn9OVLyXYpvtyrFfak.jpg",
"adult":false,
"overview":"An apocalyptic story set in the furthest reaches of our planet, in a stark desert landscape where humanity is broken, and most everyone is crazed fighting for the necessities of life. Within this world exist two rebels on the run who just might be able to restore order. There's Max, a man of action and a man of few words, who seeks peace of mind following the loss of his wife and child in the aftermath of the chaos. And Furiosa, a woman of action and a woman who believes her path to survival may be achieved if she can make it across the desert back to her childhood homeland.",
"release_date":"2015-05-13",
"genre_ids":[878,53,28,12],
"id":76341,
"original_title":"Mad Max: Fury Road",
"original_language":"en",
"title":"Mad Max: Fury Road",
"backdrop_path":"\/tbhdm8UJAb4ViCTsulYFL3lxMCd.jpg",
"popularity":32.157869,
"vote_count":3566,
"video":false,
"vote_average":7.5
},
try changing
Log.i("title", jsonPart.getString("title"));
to
Log.i(TAG, "Title: " + jsonPart.getString("title"));
and comment out the above log statement so it can be read easily
I am creating an Android application, and I am trying to retrieve data from a Restful Web-service through JSON.
I have performed a call with get and post JSON data from a Restful Web service(from a URL)
By this Tutorial
So here I need to add price * quantity
like the example below:
But I don't know how to Post this calculation for JSON data
I googled and tried few Other options....
Can any one suggest me like this kind for Post JSON data..
I followed this to POST JSON Data
But this Should be Done OnClick, it should ask add enter quantity.
Offline(db) its possible But for Custom Listview(Async listview-Online) I am Unable to Build
Please let me Know to Use for this kind...
I google many options But I am Help less....
As I understood your question I'm trying to provide answer as follow. I hope that you understand Model class concept, which makes life easier.
Step - 1 :
First create one model class and make it Serializable to pass model object, because I can see that you have two activities one for products list and second for billing. In this you may add/remove some fields as per your requirements.
public class Product implements Serializable {
public String productName;
public int price;
public int quantity;
public int total;
}
Step - 2 : Now I'm assuming that you know how to assign data to ArrayList userProducts by using gson library, link1 and link2.
Step - 3 : Next step would be to calculate total = price * quantity in listview setOnItemClickListener like this,
Product product = userProducts.get(postiton);
product.total = product.price * product.quantity;
Step - 4 : Send arraylist with Serializable object from one activity to another,
Intent intent = new Intent(ProductActivity.this, BillingActivity.class);
intent.putExtra("user_products", userProducts);
startActivity(intent);
Step - 5 : Get values in billing activity,
if (getIntent() != null) {
userProducts = (ArrayList<Product>) getIntent()
.getSerializableExtra("user_products");
}
Step - 6 : Now your question is how to post them ? The thing is that you've to create jsonarray for list of products and jsonobject for some other fields, and then you can send main jsonobject as a string, a very good tutorial.
try {
JSONObject mainJObject = new JSONObject();
JSONArray productJArray = new JSONArray();
for (int i = 0; i < userProducts.size(); i++) {
JSONObject productJObject = new JSONObject();
productJObject.put("productname", userProducts.get(i).productName);
productJObject.put("price", userProducts.get(i).price);
productJObject.put("quantity", userProducts.get(i).quantity);
productJObject.put("total", userProducts.get(i).total);
productJArray.put(productJObject);
}
mainJObject.put("products", productJArray);
mainJObject.put("grandd_total", grandTotal);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
It should look like this,
{
"products": [
{
"productname": "p1",
"price": "15",
"quantity": "6",
"total": 90
},
{
"productname": "p2",
"price": "25",
"quantity": "4",
"total": 100
}
],
"grandd_total": 190
}
You can use this json-structure data to post to the server:
{
"date": "2015-07-03",
"item": [
{
"itemname": "xyz",
"quantity": 6,
"price": 80
},
{
"itemname": "abc",
"quantity": 6,
"price": 80
}
],
"total": "960",
"currency": "Rs."
}
Everything where money is involved you should use BigDecimal how you will post data to server really doesn't meather as long data are secured.
I would use volley lib. It take care of a lot of stuff instead of you and you should really dig into, it will save you a lot of time: http://www.androidhive.info/2014/05/android-working-with-volley-library-1/
Also, I would use GSON for json objects. Its also simple for example create class:
public class Money{
String name;
int quantay;
BigDecimal rate;
BigDecimal total;
/* make seters and getters */
}
and the just create json like this:
money = new Money("name", 100, 0.54, 54);
Gson gson = new Gson();
String json = gson.toJson(money);
thats it. Well you need constructor in Money class.
how this answer help you.
you can read json right?
so by json object try this :-
Double Rate = Double.parseDouble(jsonobject.getString("Rate"));//put api parameter
int Qty= Integer.parseInt(jsonobject.getString("Qty"));
Double total = Rate * Qty;
//set total on your textview lable
textview.settext(""+total);
and save in your local database and when you need to post then post your database to server.
I would rather calculate the data before posting it to the php database. You can use something like the following:
double a = 1.50;
double b = 2.00;
double c = a * b;
Using the HTTPPost medthod (which by the way is depreciated) you need to then do something similar to the below:
public void postData(){
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yourdomain.com/post.php");
try {
List nameValuePairs = new ArrayList(1);
nameValuePairs.add(new BasicNameValuePair("data1", c));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
InputStream is = response.getEntity().getContent();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(20);
int current = 0;
while((current = bis.read()) != -1){
baf.append((byte)current);
}
text = new String(baf.toByteArray());
txtvw.setText(text);
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
Hope this helps :)
Hope this helps you , as per above ans i have checked, you need Grand_Total to post on Bill Webservice.
you just calculate and pass that data to Bill Screen like above given ans
if (getIntent() != null) {
userProducts = (ArrayList<Product>) getIntent()
.getSerializableExtra("user_products");
}
Here is one Grand Total is missing to pass as per looks in Billing screen
(Here we trying to get Grand total Rs.905)
double Grand_total = 0.0;
for(int i=0;i<userProducts.size();i++)
{
Product product = userProducts.get(postiton);
product.total = product.price * product.quantity;
Grand_total +=product.total;
}
Now you can pass all required data to Billing webservice like
try {
JSONObject mainJObject = new JSONObject();
JSONArray productJArray = new JSONArray();
for (int i = 0; i < userProducts.size(); i++) {
JSONObject productJObject = new JSONObject();
productJObject.put("productname", userProducts.get(i).productName);
productJObject.put("price", userProducts.get(i).price);
productJObject.put("quantity", userProducts.get(i).quantity);
productJObject.put("total", userProducts.get(i).total);
productJObject.put("total", userProducts.get(i).total);
productJArray.put(productJObject);
}
mainJObject.put("products", productJArray);
mainJObject.put("Grand_total", Grand_total);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I am writing an Android news reader as a learning exercise and having lots of trouble parsing the data. I have searched everywhere. The tutorials I have found use JSON streams that are of a much simpler structure than what google is sending.
Here is a snippet of the string I capture - the JSON array starts with "entries" and I am showing two entries, with the middle of the second one deleted for brevity.
{
"responseData": {
"feed": {
"feedUrl": "http://news.google.com/news?output\u003drss",
"title": "Top Stories - Google News",
"link": "http://news.google.com/news? pz\u003d1\u0026amp;ned\u003dus\u0026amp;hl\u003den",
"author": "",
"description": "Google News",
"type": "rss20",
"entries": [{
"title": "Major air rescue planned in flooded Colorado county - Fox News",
"link": "http://news.google.com/news/url? sa\u003dt\u0026fd\u003dR\u0026usg\u003dAFQjCNHCJS1c-eurSg- 8tAt0PjZ4tiaLdA\u0026url\u003dhttp://www.foxnews.com/weather/2013/09/15/colorado-braces-for-more-heavy-rain-deadly-floods/",
"author": "",
"publishedDate": "Mon, 16 Sep 2013 04:49:21 -0700",
"contentSnippet": "U.S. News \u0026 World ReportMajor air rescue planned in flooded Colorado countyFox NewsResidents of Boulder County, Colorado are ...",
"content": "\u003ctable border\u003d\"0\" cellpadding\u003d\"2\" cellspacing\u003d\"7\" 3d\"\"border\u003d\"1\" width\u003d\"80\" height\u003d\"80\"\u003e\u003cbr\u003e\u003cfont size\u003d\"-2\"\u003eU.S. News \u0026amp; 03e\u003c/font\u003e\u003cbr\u003e\u003cfont size\u003d\"-1\"\u003eResidents of Boulder County, Colorado are being asked to help guide helicopter pilots to their locations Monday as a major air rescue is being planned to take advantage of a clear weather forecast. \u0026quot;The pilots are going to go anywhere and everywhere they \u003cb\u003e...\u003c/b\u003e\u003c/font\u003e\u003cbr\u003e\u003cfont size\u003d\"-1\"\u003e\u003ca href\u003d\"http://news.google.com/news/url? sa\u003dt\u0026amp;fd\u003dR\u0026amp;usg\u003dAFQjCNHc6lIe9u_YShLkh7NV5WR9rO6YHQ\u0026amp; url\u003dhttp://www.therepublic.com/view/story/b663f09bbf48403c9041a86623fe428e/CO-- Colorado-Flooding-National-Guard\"\u003eNational Guard members trapped during evacuations from flooded Colorado town\u003c/a\u003e\u003cfont size\u003d\"-1\" color\u003d\"#6f6f6f\"\u003eThe Republic\u003c/font\u003e\u003c/font\u003e\u003cbr\u003e\u003cfont size\u003d\"-1\"\u003e\u003ca href\u003d\"http://news.google.com/news/url? sa\u003dt\u0026amp;fd\u003dR\u0026amp;usg\u003dAFQjCNFij70BTG-5dO69JM0BVO32S0S- aA\u0026amp;url\u003dhttp://www.cnn.com/2013/09/15/us/colorado-flooding/? hpt%3Dhp_t1\"\u003eColorado floods: More than 500 still unaccounted for as \u0026#39;devastating\u0026#39; rain looms\u003c/a\u003e\u003cfont size\u003d\"-1\" Radio\u003c/a\u003e\u003c/font\u003e\u003cbr\u003e\u003cfont size\u003d\"-1\"\u003e\u003ca href\u003d\"http://news.google.com/news/more? ncl\u003ddQHisuNx5u46LtMZh5z80DBxCCRjM\u0026amp;ned\u003dus\u0026amp;topic\u003dh\"\u003e\u 003cb\u003eall 1,507 news articles »\u003c/b\u003e\u003c/a\u003e\u003c/font\u003e\u003c/div\u003e\u003c/font\u003e\u003c/td\u0 03e\u003c/tr\u003e\u003c/table\u003e",
"categories": ["Top Stories"]
},
{
"title": "Costa Concordia salvage begins: Will ship stay in one piece during righting? - CNN",
"link": "http://news.google.com/news/url? sa\u003dt\u0026fd\u003dR\u0026usg\u003dAFQjCNFD_8vBF3Gb6B2_6DnbCDwMELEkFQ\u0026url\u003dhtt p://www.cnn.com/2013/09/15/world/europe/italy-costa-concordia-salvage/",
"author": "",
....deletedcontentsforbrevity...."categories": ["Top Stories"]
}]
}
},
"responseDetails": null,
"responseStatus": 200
}
So I have successfully captured the string and now want to create a JSONArray and extract the JSONObjects from it. Here is the code:
private void parseJSONString( JSONObject Jobj) throws IOException, JSONException {
try {
// Getting Array of news
newsItems = Jobj.getJSONArray(ENTRIES);
// looping through All Contacts
for(int i = 0; i < newsItems.length(); i++){
JSONObject c = newsItems.getJSONObject(i);
// Storing each json item in variable
String title = c.getString(TITLE);
String link = c.getString(LINK);
String author = c.getString(AUTHOR);
String pubDate = c.getString(PUBLISHED_DATE);
String content = c.getString(CONTENT);
}
} catch (JSONException e) {
e.printStackTrace();
}
I am catching the JSONException with the message "No values for entries" from the very
first line of code: newsItems = Jobj.getJSONArray(ENTRIES);
The parameter jobj and call to this method is created onPostExecute like this:
protected void onPostExecute(Void result) {
mTextView.setText(mDataString);
if (mDataString != null)
try {
mJSONObj = new JSONObject(mDataString);
parseJSONString(mJSONObj);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
Log.e("JSON Parser", "Error converting string to json " + e.toString());
}
}
Yet as you can see, "entries" clearly precedes the array marker "[" in the text file. I am truly stumped. Would appreciate a little help.
You must firstly get:
responseData -> feed -> entries
JSONObject responseData = Jobj.getJSONObject("responseData");
JSONObject feed = responseData.getJSONObject("feed");
and only after:
newsItems = feed.getJSONArray("entries");