I have a string from http request and i want to replace multiple chars and strings with others.How i can do this?With Array for more efficient way?
String result =" "hourly": [ {"cloudcover": "0", "humidity": "93", "precipMM": "0.0", "pressure": "1013", "sigHeight_m": "0.7", "swellDir": "70", "swellHeight_m": "0.5", "swellPeriod_secs": "1.0", "tempC": "9", "tempF": "48", "time": "0", "v";
String result2 = result.replace("{", " ");
String result3 = result2.replace("}", " ");
String result4 = result3.replace("[", " ");
String result5 = result4.replace("]", " ");
String result6 = result5.replace("\"", "");
String result7 = result6.replaceAll("......", " ");
String result8 = result7.replaceAll("cloudcover", "\n \ncloudcover");
String result9 = result8.replaceAll("winddir:", " \nwinddir:");
String result10 = result9.replaceAll("tempC:", " \ntempC:");
WeatherInfos.setText( result10 );//Shows the weather info
Try following
String result = "{\"hourly\": [ {\"cloudcover\": \"15\", \"humidity\": \"93\", \"pressure\": \"1013\", \"tempC\": \"9\", \"winddir\": \"25\"}]}";
if(!result.startsWith("{"))
result = "{" + result + "}";
JSONObject JSONResult = new JSONObject(result);
JSONResult = (JSONObject) JSONResult.getJSONArray("hourly").get(0);
String cloudcover = JSONResult.getString("cloudcover");
String tempC= JSONResult.getString("tempC");
String winddir= JSONResult.getString("winddir"); //i do not see winddir in your result
Toast.makeText(getapplicationContext(), "Cloud Cover is "+ cloudcover , Toast.LENGTH_LONG).show();
now print cloudcover, winddir and tempC where ever you want.
Related
I want my TextView contain 2 String of JSON data.
example.json
{
"volumeInfo": {
"title": "Computer Architecture",
"subTitle": "A Quantitative Approach"
}
So, from that JSON i want my TextView to be: Computer Architecture: A Quantitative Approach. How should i do? Thanks.
I only want using one TextView
Just do it
String title = "Computer Architecture";
String subtitle = "A Quantitative Approach";
TextView.setText(title + ": " + subtitle);
You can concatenate Strings and then set it to TextView like below:
String title = "Computer Architecture";
String subtitle = "A Quantitative Approach";
yourTextView.setText(title + "," + subtitle);
//Please check the below code will help you as you want to set the text.
String response = "{" +
" \"volumeInfo\": {" +
" \"title\": \"Computer Architecture\"," +
" \"subTitle\": \"A Quantitative Approach\"}" +
"}";
try {
String title = "", subTitle = "";
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.has("volumeInfo")) {
JSONObject jsonObject1 = jsonObject.getJSONObject("volumeInfo");
if (jsonObject1.has("title")) {
title = jsonObject1.getString("title");
}
if (jsonObject1.has("subTitle")) {
subTitle = jsonObject1.getString("subTitle");
}
String combineString = title + ": " + subTitle;
TextView textView = findViewById(R.id.textView);
textView.setText(combineString);
}
} catch (JSONException e) {
e.printStackTrace();
}
My JSON:
{
"response_code": 200,
"error": false,
"train_name": "KCG YPR EXP",
"train_num": "17603",
"pnr": "1234567890",
"failure_rate": 19.346153846153847,
"doj": "20-8-2015",
"chart_prepared": "Y",
"class": "SL",
"total_passengers": 2,
"train_start_date": {
"month": 8,
"year": 2015,
"day": 20
},
"from_station": {
"code": "KCG",
"name": "KACHEGUDA"
},
"boarding_point": {
"code": "KCG",
"name": "KACHEGUDA"
},
"to_station": {
"code": "YPR",
"name": "YESVANTPUR JN"
},
"reservation_upto": {
"code": "YPR",
"name": "YESVANTPUR JN"
},
"passengers": [
{
"no": 1,
"booking_status": "S7,58,GN",
"current_status": "S7,58",
"coach_position": 9
},
{
"no": 2,
"booking_status": "S7,59,GN",
"current_status": "S7,59",
"coach_position": 9
}
]
}
What I did so far:
if(jsonStr!=null)
{
try
{
JSONObject object=new JSONObject(jsonStr);
JSONArray jsonArray=object.getJSONArray("passengers");
for (int i=0;i<=jsonArray.length();i++)
{
JSONObject o=jsonArray.getJSONObject(i);
int no= Integer.parseInt(o.optString("no").toString());
String booking_status=o.getString("Booking Status");
String current_status=o.getString("Current Status");
String coach_position=o.getString("Coach Position");
JSONObject data=o.getJSONObject("details");
String train_name = data.getString("Train Name");
int train_num = Integer.parseInt(data.optString("train number").toString());
int pnr = Integer.parseInt(data.optString("pnr").toString());
String chart_prepared = data.getString("Chart Prepared");
int total_passengers=Integer.parseInt(data.optString("total passengers").toString());
JSONObject date=data.getJSONObject("tarin_start_date");
int month=Integer.parseInt(data.optString("month").toString());
int year=Integer.parseInt(data.optString("year").toString());
int day=Integer.parseInt(data.optString("day").toString());
JSONObject co=date.getJSONObject("from_station");
String code=co.getString("code");
String name=co.getString("name");
JSONObject co1=co.getJSONObject("boarding_point");
String code1=co1.getString("code");
String name1=co1.getString("name");
JSONObject co2=co1.getJSONObject("to_station");
String code2=co2.getString("code");
String name2=co2.getString("name");
JSONObject co3=co2.getJSONObject("from_station");
String code3=co3.getString("code");
String name3=co3.getString("name");
HashMap<String,String> dtail=new HashMap<>();
dtail.put("no", String.valueOf(no));
dtail.put("Booking Staus",booking_status);
dtail.put("Current Staus",current_status);
dtail.put("Coach Positon",coach_position);
dtail.put("Train Name",train_name);
dtail.put("Train Number", String.valueOf(train_num));
dtail.put("pnr", String.valueOf(pnr));
dtail.put("chart prepared",chart_prepared);
dtail.put("total passengers", String.valueOf(total_passengers));
dtail.put("month", String.valueOf(month));
dtail.put("year", String.valueOf(year));
dtail.put("day", String.valueOf(day));
dtail.put("code",code);
dtail.put("name",name);
dtail.put("code",code1);
dtail.put("name",name1);
dtail.put("code",code2);
dtail.put("name",name2);
dtail.put("code",code3);
dtail.put("name",name3);
dataList.add(dtail);
}
}
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;
}
Here is your solution.
Hope this will help you. Whenever you work with JSON check all key name. It should always same as response key name
if (jsonStr != null) {
try {
JSONObject object = new JSONObject(jsonStr);
HashMap<String, String> dtail = new HashMap<>();
JSONArray jsonArray = object.getJSONArray("passengers");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject o = jsonArray.getJSONObject(i);
int no = Integer.parseInt(o.optString("no").toString());
String booking_status = o.getString("booking_status");
String current_status = o.getString("current_status");
String coach_position = o.getString("coach_position");
dtail.put("no", String.valueOf(no));
dtail.put("Booking Staus", booking_status);
dtail.put("Current Staus", current_status);
dtail.put("Coach Positon", coach_position);
}
String train_name = object.getString("train_name");
int train_num = Integer.parseInt(object.optString("train_num").toString());
int pnr = Integer.parseInt(object.optString("pnr").toString());
String chart_prepared = object.getString("chart_prepared");
int total_passengers = Integer.parseInt(object.optString("total_passengers").toString());
JSONObject date = object.getJSONObject("train_start_date");
int month = Integer.parseInt(date.optString("month").toString());
int year = Integer.parseInt(date.optString("year").toString());
int day = Integer.parseInt(date.optString("day").toString());
JSONObject co = object.getJSONObject("from_station");
String code = co.getString("code");
String name = co.getString("name");
JSONObject co1 = object.getJSONObject("boarding_point");
String code1 = co1.getString("code");
String name1 = co1.getString("name");
JSONObject co2 = object.getJSONObject("to_station");
String code2 = co2.getString("code");
String name2 = co2.getString("name");
JSONObject co3 = object.getJSONObject("reservation_upto");
String code3 = co3.getString("code");
String name3 = co3.getString("name");
dtail.put("Train Name", train_name);
dtail.put("Train Number", String.valueOf(train_num));
dtail.put("pnr", String.valueOf(pnr));
dtail.put("chart prepared", chart_prepared);
dtail.put("total passengers", String.valueOf(total_passengers));
dtail.put("month", String.valueOf(month));
dtail.put("year", String.valueOf(year));
dtail.put("day", String.valueOf(day));
dtail.put("code", code);
dtail.put("name", name);
dtail.put("code", code1);
dtail.put("name", name1);
dtail.put("code", code2);
dtail.put("name", name2);
dtail.put("code", code3);
dtail.put("name", name3);
dataList.add(dtail);
} catch (final JSONException e) {
Log.e("Json", "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
Hope this will help :-
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dummy);
String str = "{\n" +
" \"response_code\": 200,\n" +
" \"error\": false,\n" +
" \"train_name\": \"KCG YPR EXP\",\n" +
" \"train_num\": \"17603\",\n" +
" \"pnr\": \"1234567890\",\n" +
" \"failure_rate\": 19.346153846153847,\n" +
" \"doj\": \"20-8-2015\",\n" +
" \"chart_prepared\": \"Y\",\n" +
" \"class\": \"SL\",\n" +
" \"total_passengers\": 2,\n" +
" \"train_start_date\": {\n" +
" \"month\": 8,\n" +
" \"year\": 2015,\n" +
" \"day\": 20\n" +
" },\n" +
" \"from_station\": {\n" +
" \"code\": \"KCG\",\n" +
" \"name\": \"KACHEGUDA\"\n" +
" },\n" +
" \"boarding_point\": {\n" +
" \"code\": \"KCG\",\n" +
" \"name\": \"KACHEGUDA\"\n" +
" },\n" +
" \"to_station\": {\n" +
" \"code\": \"YPR\",\n" +
" \"name\": \"YESVANTPUR JN\"\n" +
" },\n" +
" \"reservation_upto\": {\n" +
" \"code\": \"YPR\",\n" +
" \"name\": \"YESVANTPUR JN\"\n" +
" },\n" +
" \"passengers\": [\n" +
" {\n" +
" \"no\": 1,\n" +
" \"booking_status\": \"S7,58,GN\",\n" +
" \"current_status\": \"S7,58\",\n" +
" \"coach_position\": 9\n" +
" },\n" +
" {\n" +
" \"no\": 2,\n" +
" \"booking_status\": \"S7,59,GN\",\n" +
" \"current_status\": \"S7,59\",\n" +
" \"coach_position\": 9\n" +
" }\n" +
" ]\n" +
"}";
parseJson(str);
}
private void parseJson(String jsonStr) {
HashMap<String, String> dtail = new HashMap<>();
if (jsonStr != null) {
try {
JSONObject object = new JSONObject(jsonStr);
int responseCode = object.getInt("response_code");
boolean error = object.getBoolean("error");
String train_name = object.getString("train_name");
int train_num = object.getInt("train_num");
int pnr = object.getInt("pnr");
double failurerate = object.getDouble("failure_rate");
String dateofJoin = object.getString("doj");
String chart = object.getString("chart_prepared");
String Class = object.getString("class");
int total_passengers = object.getInt("total_passengers");
JSONObject date = object.getJSONObject("train_start_date");
int month = date.getInt("month");
int year = date.getInt("year");
int day = date.getInt("day");
JSONObject co = object.getJSONObject("from_station");
String code = co.getString("code");
String name = co.getString("name");
JSONObject co1 = object.getJSONObject("boarding_point");
String code1 = co1.getString("code");
String name1 = co1.getString("name");
JSONObject co2 = object.getJSONObject("to_station");
String code2 = co2.getString("code");
String name2 = co2.getString("name");
JSONObject co3 = object.getJSONObject("from_station");
String code3 = co3.getString("code");
String name3 = co3.getString("name");
JSONArray jsonArray = object.getJSONArray("passengers");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
int no = jsonObject.getInt("no");
String booking_status = jsonObject.getString("booking_status");
String current_status = jsonObject.getString("current_status");
int coach_position = jsonObject.getInt("coach_position");
dtail.put("no", String.valueOf(no));
dtail.put("booking_status", booking_status);
dtail.put("current_status", current_status);
dtail.put("coach_position", String.valueOf(coach_position));
}
dtail.put("responseCode", String.valueOf(responseCode));
dtail.put("error", "" + error);
dtail.put("Train Name", train_name);
dtail.put("dateofJoin", dateofJoin);
dtail.put("chart", chart);
dtail.put("Class", Class);
dtail.put("Train Number", String.valueOf(train_num));
dtail.put("pnr", String.valueOf(pnr));
dtail.put("FAILURE_RATE", String.valueOf(failurerate));
dtail.put("total passengers", String.valueOf(total_passengers));
dtail.put("month", String.valueOf(month));
dtail.put("year", String.valueOf(year));
dtail.put("day", String.valueOf(day));
dtail.put("code", code);
dtail.put("name", name);
dtail.put("code", code1);
dtail.put("name", name1);
dtail.put("code", code2);
dtail.put("name", name2);
dtail.put("code", code3);
dtail.put("name", name3);
Log.e("Result------", "" + dtail);
} 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();
}
});
}
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Need Help
I have Json through which i have to retrieve objects but unable to retrieve.
I have used multiple objects also to retrieve but no success.
JSON:
{
"status": 1,
"data": [{
"restaurent_id": "1",
"user_id": "6",
"zone_id": "1",
"restaurentAddress": {
"restaurent_address_id": "1"
},
"restaurentInfo": {
"restaurent_info_id": "1",
"restaurent_bussiness_owner_name": "Vijay"
},
"restaurentSetting": {
"restaurent_setting_id": "1",
"minimum_purcase": "200",
"payment_method_id": "1",
"title": "Best Hotel"
},
"zone": {
"zone_id": "1",
"by_zipcode": "1"
}
}]
}
and i want to fetch restaurentAddress and restaurentInfo
MY mainActivity.java file
package com.example.premi.jsonlist;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView output = (TextView) findViewById(R.id.textView1);
String strJson="{\n" +
"\t\"status\": 1,\n" +
"\t\"data\": [{\n" +
"\t\t\"restaurent_id\": \"1\",\n" +
"\t\t\"user_id\": \"6\",\n" +
"\t\t\"zone_id\": \"1\",\n" +
"\t\t\"restaurentAddress\": {\n" +
"\t\t\t\"restaurent_address_id\": \"1\"\n" +
"\t\t},\n" +
"\t\t\"restaurentInfo\": {\n" +
"\t\t\t\"restaurent_info_id\": \"1\",\n" +
"\t\t\t\"restaurent_bussiness_owner_name\": \"Vijay\"\n" +
"\t\t},\n" +
"\t\t\"restaurentSetting\": {\n" +
"\t\t\t\"restaurent_setting_id\": \"1\",\n" +
"\t\t\t\"minimum_purcase\": \"200\",\n" +
"\t\t\t\"payment_method_id\": \"1\",\n" +
"\t\t\t\"title\": \"Best Hotel\"\n" +
"\t\t},\n" +
"\t\t\"zone\": {\n" +
"\t\t\t\"zone_id\": \"1\",\n" +
"\t\t\t\"by_zipcode\": \"1\"\n" +
"\t\t}\n" +
"\n" +
"\t}]\n" +
"}";
String dataoutput = "";
try {
JSONObject jsonRootObject = new JSONObject(strJson);
//Get the instance of JSONArray that contains JSONObjects
JSONObject status = jsonRootObject.optJSONObject("status");
JSONArray Dataarray =status.getJSONArray("data");
//Iterate the jsonArray and print the info of JSONObjects
for(int i=0; i < Dataarray.length(); i++){
JSONObject jsonObject = Dataarray.getJSONObject(i);
JSONObject Data = jsonObject.getJSONObject("restaurentAddress");
for(int j = 0 ; j < Data.length(); j++){
JSONObject GetData =Data.getJSONObject(String.valueOf(j));
int id = Integer.parseInt(GetData.getString("restaurent_address_id"));
String postcode = GetData.getString("postcode");
String addresss = GetData.getString("restaurent_address");
dataoutput += " : \n id= "+ id +" \n postcode= "+ postcode +" \n address= "+ addresss +" \n ";
}}
output.setText(dataoutput);
} catch (JSONException e) {e.printStackTrace();}
}
}
Try this out:
try {
JSONObject object = (JSONObject) new JSONTokener(YOUR_JSON_STRING).nextValue();
String restaurentAddressId = object.getJSONArray("data").getJSONObject(0).getJSONObject("restaurentAddress").getString("restaurent_address_id");
String restaurentInfoId = object.getJSONArray("data").getJSONObject(1).getJSONObject("restaurentInfo").getString("restaurent_info_id");
String restaurentBizOwnerName = object.getJSONArray("data").getJSONObject(1).getJSONObject("restaurentInfo").getString("restaurent_business_owner_name");
}
catch (JSONException e) {
}
Its Done I tried this
try {
JSONObject jsonRootObject = new JSONObject(strJson);
//Get the instance of JSONArray that contains JSONObjects
JSONArray mainnode =jsonRootObject.getJSONArray("data");
//Iterate the jsonArray and print the info of JSONObjects
for(int i=0; i < mainnode.length(); i++){
JSONObject jsonObject = mainnode.getJSONObject(i);
JSONObject Data = jsonObject.getJSONObject("restaurentInfo");
int id = Integer.parseInt(Data.getString("restaurent_info_id"));
String postcode = Data.getString("restaurent_phone_number");
String addresss = Data.getString("restaurent_bussiness_owner_name");
dataoutput += " : \n restaurent_id= "+ id +" \n restaurent_info_id= "+ postcode +" \n restaurent_address_id= "+ addresss +" \n ";
}
output.setText(dataoutput);
} catch (JSONException e) {e.printStackTrace();}
}
I just removed Status Object
and another for loop Thanks For the Help Got little Bit Help from You :)
This question already has answers here:
Parsing json with android
(4 answers)
Closed 8 years ago.
I am trying to parse this json:
[{
"codError": 0,
"msg": "OK"
}, {
"id": 1,
"role": {
"id": 4,
"name": "Super",
"description": "Roling.",
"rights": [],
"superuser": true,
"active": true,
"optimisticLock": 0
},
"now": null,
"points": [],
"firstName": null,
"lastName": null,
"loginName": "admin",
"password": null,
"connected": true,
"active": true,
"optimisticLock": null
},
["U4"]
]
I am not able to get the value of role id and loginName, my code is here:
private static final String TAG_ROLE = "role";
private static final String TAG_ID = "id";
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONArray jsonarr =new JSONArray(jsonStr);
JSONObject jobj=jsonarr.getJSONObject(1);
JSONObject role =jobj.getJSONObject(TAG_ROLE);
String role_id = role.getString(TAG_ID);
} catch (JSONException e) {
e.printStackTrace();
}
I debug my app and String role_id doesn´t get any value, what is the problem of the code? Thank you
JSONArray array;
array = new JSONArray(jsonStr);
JSONObject obj = array.getJSONObject(1);
JSONObject obj2 = obj.getJSONObject("role");
int id = obj2.getInt("id");
String name = obj2.getString("name");
In case you aren't getting any values, you might want to check if the response is exactly how you're expecting it to be. Also, check the values of TAG_ROLE, TAG_ID.
Edit 1 :
String jsonStr = "[{\n \"codError\": 0,\n \"msg\": \"OK\"\n}, {\n \"id\": 1,\n \"role\": {\n \"id\": 4,\n \"name\": \"Super\",\n \"description\": \"Roling.\",\n \"rights\": [],\n \"superuser\": true,\n \"active\": true,\n \"optimisticLock\": 0\n },\n \"now\": null,\n \"points\": [],\n \"firstName\": null,\n \"lastName\": null,\n \"loginName\": \"admin\",\n \"password\": null,\n \"connected\": true,\n \"active\": true,\n \"optimisticLock\": null\n},\n[\"U4\"]\n\n]";
try {
JSONArray array;
array = new JSONArray(jsonStr);
JSONObject obj = array.getJSONObject(1);
JSONObject obj2 = obj.getJSONObject("role");
int id = obj2.getInt("id");
String name = obj2.getString("name");
System.out.println(id);
System.out.println(name);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I'd like to parse the following items from JSON data below: title, year, runtime, critics consensus, the theater release date, the synopsis, poster thumbnails, and poster originals. But when I parse my data I get a JSON Exception: No value for TAG_TITLE, and basically nothing happens.
{"query": {
"count": 30,
"created": "2014-01-16T14:39:33Z",
"lang": "en-US",
"results": {
"movies": [
{
"id": "13065",
"title": "Gladiator",
"year": "2000.0",
"mpaa_rating": "R",
"runtime": "171.0",
"critics_consensus": "Ridley Scott and an excellent cast successfully convey the intensity of Roman gladitorial combat as well as the political intrigue brewing beneath.",
"release_dates": {
"theater": "2000-05-05",
"dvd": "2000-11-21"
},
"ratings": {
"critics_rating": "Certified Fresh",
"critics_score": "76.0",
"audience_rating": "Upright",
"audience_score": "87.0"
},
"synopsis": "",
"posters": {
"thumbnail": "http://content6.flixster.com/movie/11/16/89/11168944_mob.jpg",
"profile": "http://content6.flixster.com/movie/11/16/89/11168944_pro.jpg",
"detailed": "http://content6.flixster.com/movie/11/16/89/11168944_det.jpg",
"original": "http://content6.flixster.com/movie/11/16/89/11168944_ori.jpg"
},
"abridged_cast": [
{
"name": "Russell Crowe",
"id": "162652569",
"characters": "Maximus"
},
{
"name": "Joaquin Phoenix",
"id": "162655394",
"characters": "Commodus"
},
{
"name": "Connie Nielsen",
"id": "162653203",
"characters": "Lucilla"
},
{
"name": "Oliver Reed",
"id": "162662908",
"characters": "Proximo"
},
{
"name": "Derek Jacobi",
"id": "162656362",
"characters": "Gracchus"
}
],
"alternate_ids": {
"imdb": "0172495"
},
"links": {
"self": "http://api.rottentomatoes.com/api/public/v1.0/movies/13065.json",
"alternate": "http://www.rottentomatoes.com/m/gladiator/",
"cast": "http://api.rottentomatoes.com/api/public/v1.0/movies/13065/cast.json",
"clips": "http://api.rottentomatoes.com/api/public/v1.0/movies/13065/clips.json",
"reviews": "http://api.rottentomatoes.com/api/public/v1.0/movies/13065/reviews.json",
"similar": "http://api.rottentomatoes.com/api/public/v1.0/movies/13065/similar.json"
}
}
This is the code for extracting the data I want:
jsonObject = new JSONObject(result);
JSONObject queryJSONObject = jsonObject.getJSONObject("query");
JSONObject resultsJSONObject = queryJSONObject.getJSONObject("results");
JSONArray moviesJSONArray = resultsJSONObject.getJSONArray("movies");
for(int i = 0; i < moviesJSONArray.length(); i++){
JSONObject c = moviesJSONArray.getJSONObject(i);
String title = c.getString("TAG_TITLE");
String year = c.getString("TAG_YEAR");
String mpaa_rating = c.getString("TAG_RATING");
String runtime = c.getString("TAG_RUNTIME");
String critics_consensus = c.getString("TAG_CONSENSUS");
JSONObject dates = c.getJSONObject("release_dates");
String theater = dates.getString("TAG_THEATER");
JSONObject posters = c.getJSONObject("posters");
String thumbnail_posters = posters.getString("TAG_TBPOSTER");
String original_posters = posters.getString("TAG_ORIPOSTER");
Log.e(TAG,
", Title: " + title
+ ", Year: " + year
+ ", Rating: " + mpaa_rating
+ ", Runtime: " + runtime
+ ", Consensus :" + critics_consensus
+ ", Theater date: " + theater
+ ". Poster small: " + thumbnail_posters
+ ", Poster big: " + original_posters
);
HashMap<String, String> movie = new HashMap<String, String>();
movie.put(TAG_TITLE, title);
movie.put(TAG_YEAR, year);
movie.put(TAG_RATING, mpaa_rating);
movie.put(TAG_RUNTIME, runtime);
movie.put(TAG_CONSENSUS, critics_consensus);
movie.put(TAG_THEATER, theater);
movie.put(TAG_TBPOSTER, thumbnail_posters);
movie.put(TAG_ORIPOSTER, original_posters);
moviesList.add(movie);
And before my OnCreate I'm using these Strings for the TAGS:
private static final String TAG_CONSENSUS = "critics_consensus";
private static final String TAG_RATING = "mpaa_rating";
private static final String TAG_YEAR = "year";
private static final String TAG_THEATER = "theater";
private static final String TAG_TITLE = "title";
private static final String TAG_RUNTIME = "runtime";
private static final String TAG_DATE = "theater";
private static final String TAG_TBPOSTER = "thumbnail_posters";
private static final String TAG_ORIPOSTER = "original_posters";
JSONArray movies = null;
ArrayList<HashMap<String, String>> moviesList;
My TAG_TITLE is "title" which is also used in the JSON Data so I'm at a loss as to why I get this error? Or is my code wrong? Thanks in advance
Shouldn't you do
String title = c.getString(TAG_TITLE);
instead of
String title = c.getString("TAG_TITLE");
?
You should have to either write String directly like
JSONObject jsonobject = new JSONObject(jsonString);
JSONObject queryjson = jsonobject.getJSONObject("query");
String count = queryjson.getString("count");
OR
//This Code is As per Your Coding
JSONObject jsonobject = new JSONObject(jsonString);
JSONObject queryjson = jsonobject.getJSONObject(TAG_QUERY);
String count = queryjson.getString(TAG_COUNT);
Inshort Just Remove The " " before Or After String Name TAG_..