I can not retrieve all key values from JSON object retrieved from HTTP request.
This is the returned JSON object from http request:
{"data":[{"movie_id":3,"movie_name":"Promithius","genre":"a dude","year":"2016","rating":45}]}
my Android Code:
try {
//HttpJsonParser httpJsonParser = new HttpJsonParser();
JSONObject JSonObj = (JSONObject) new
JSONTokener(result).nextValue();
String mymovie = JSonObj.getString("movie_name" );
String movieGenre = JSonObj.getString("genre" );
etResponse.setText("movie=" + mymovie + " genre=" +
movieGenre);
} catch (JSONException e) {
etResponse.setText("ERROR=" + e.getMessage());
e.printStackTrace();
}
When I run it in emulator with only:
String mymovie = JSonObj.getString("movie_name" );
etResponse.setText("movie=" + mymovie;
I get back the Movie name with no error. So the issue is I can retrieve movie_name but no Genre.
Error returned says "No value for genre"
Thanks in advance.
I think the data is JSONArray.
String result = "{\"data\":[{\"movie_id\":3,\"movie_name\":\"Promithius\",\"genre\":\"a dude\",\"year\":\"2016\",\"rating\":45}]}";
try {
JSONObject JSonObj = (JSONObject) new JSONTokener(result).nextValue();
JSONArray data = JSonObj.getJSONArray("data");
for (int i=0; i<data.length(); i++){
JSONObject jsonObject = data.getJSONObject(i);
String mymovie = jsonObject.getString("movie_name" );
String movieGenre = jsonObject.getString("genre" );
String dest = "movie=" + mymovie + " genre=" + movieGenre;
Log.d(TAG, dest);
}
} catch (JSONException e) {
e.printStackTrace();
}
Below is the code that finally worked for me. I hope it can help someone else.
try{
JSONObject object = new JSONObject(result);
JSONArray Jarray = object.getJSONArray("data");
object = Jarray.getJSONObject(0);
String MovieName = object.getString("movie_name");
String Genre = object.getString("genre");
String Rating = object.getString("rating");
String Year = object.getString("year");
etResponse.setText("Movie Name = " + MovieName + " \n Genre = " +
Genre + "\n Rating = " + Rating + " \n Year = " + Year );
} catch (JSONException e) {
etResponse.setText("JSONException: " + e.getMessage());
}
Related
Searching for solution of that. Sample of Java code:
public void loadPositions(JSONObject result){
try {
JSONObject jObject = result.getJSONObject("points");
Iterator<String> keys = jObject.keys();
while (keys.hasNext()) {
String key = keys.next();
Log.v("list key", key);
if(jObject.get(key) instanceof JSONObject) {
JSONObject innerJObject = jObject.getJSONObject(key);
String lat = innerJObject.getString("lat");
String lon = innerJObject.getString("lon");
Log.i("details", "lat = " + lat + ", " + "lon = " + lon);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
JSON data:
{
"points":{
"C50D15525":[
{
"lat":"51.643257329609156",
"lon":"17.798963651975885"
},
{
"lat":"51.643257329609156",
"lon":"17.798963651975885"
}
],
"BFFCDE4AF":[
{
"lat":"51.6434779",
"lon":"17.7993028"
},
{
"lat":"51.6434779",
"lon":"17.7993028"
},
{
"lat":"51.6434779",
"lon":"17.7993028"
}
]
}
}
Code above give me only list key, but I want LAT & LON from many points like "BFFCDE4AF" and "C50D15525". I've tried in many ways... JSON data is valid.
You can achive it through this
For example
points.C50D15525["lat"]
but you need to extract json through apply any looping and associative concept.
Inside the "points" object your JSON has an Array object, which you need to get with the getJSONArray() method. Loop through the JSONArray and get the "lat" and "lon" objects.
public void loadPositions(JSONObject result){
try {
JSONObject jObject = result.getJSONObject("points");
Iterator<String> keys = jObject.keys();
while (keys.hasNext()) {
String key = keys.next();
Log.v("list key", key);
JSONArray jArray = jObject.getJSONArray(key);
for (int i=0; i < jArray.length(); i++){
JSONObject obj = jArray.getJSONObject(i);
String lat = obj.optString("lat", "NA"));
String lon = obj.optString("lon", "NA"));
Log.i("details","key = " + key + " coor count = " + i + " lat = " + lat + ", " + "lon = " + lon);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Since I have not tested this, please let me know if you have any issues.
On click of selected date, I want to display related tasks or events.
public static List<ScheduledTasks> getResponse() {
String res = "[{\n" +
"\t\"scheduleId\": \"999\",\n" +
"\t\"eventType\": \"first\",\n" +
"\t\"impacts\": \"high\",\n" +
"\t\"startDate\": 27032018,\n" +
"\t\"endDate\": 27032018,\n" +
"\t\"machineOwner\": \"Nilesh\",\n" +
"\t\"description\": \"good\",\n" +
"\t\"status\": \"working\"\n" +
"}, ...
"}]";
return new Gson().fromJson(res, new TypeToken<List<ScheduledTasks>>(){}.getType());
this is the JSON.
Using the below
LayoutManager = new LinearLayoutManager(this);
String s = getIntent().getStringExtra("dateselected");
ScheduledTasks=getResponse();
adapter = new RecyclerAdapter(ScheduledTasks);
recyclerView.setAdapter(adapter);
List<ScheduledTasks>
I want to display only tasks for selected date.
String S date needs to be matched with json response and show particular tasks.
for date 27 only the tasks on that day should be displated.
try changing your getResponse method a bit like this so you can filter by date
public static List<ScheduledTasks> getResponse(String dateselected) {
String res = "[{\n" +
"\t\"scheduleId\": \"999\",\n" +
"\t\"eventType\": \"first\",\n" +
"\t\"impacts\": \"high\",\n" +
"\t\"startDate\": 27032018,\n" +
"\t\"endDate\": 27032018,\n" +
"\t\"machineOwner\": \"Nilesh\",\n" +
"\t\"description\": \"good\",\n" +
"\t\"status\": \"working\"\n" +
"}, ...
"}]";
JSONArray array= null;
JSONArray filter=new JSONArray();
try {
//change res to a JsonArray object so i can filter
array = new JSONArray(res);
try {
for (int i=0; i<array.length();i++){
String date=array.getJSONObject(i).has("startDate")?array.getJSONObject(i).getString("startDate"):"";
//if i match selected date i pick it
if (!TextUtils.isEmpty(date)&&date.equals(dateselected))
filter.put(array.getJSONObject(i));
}
}catch (JSONException e) {
e.printStackTrace();
}
} catch (JSONException e) {
e.printStackTrace();
}
//res
res=filter.toString();
return new Gson().fromJson(res, new TypeToken<List<ScheduledTasks>>() {
}.getType());
}
I have his json and i need to retrieve array of images from images Variable..
this my json :
{
id: 215,
title: " this is title",
image: "1464958558.jpg",
description: "description",
images: "["1464958558.jpg","1464958559.jpg","1464958561.jpg","1464958563.jpg","1464958564.jpg","1464958568.jpg","1464958569.jpg","1464958570.jpg","1464958573.jpg","1464958574.jpg"]",
user_name: "user name",
telephone: "0123456789"
}
i want to retrieve this images array and display it in grid view... and i can't find any response in logcat
my doInBackGround()
#Override
protected Integer doInBackground(String... arg0) {
// Building Parameters
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
ID = mCursor.getString(ArticleLoader.Query._ID);
String jsonStr = sh.makeServiceCall(String.valueOf(Config.BASE_URL));
//jsonStr = sh.makeServiceCall(url + 373); //or url + ID
Log.i(TAG, "doInBackground Image: " + String.valueOf(Config.BASE_URL));
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
GridItem item;
item = new GridItem();
Log.i(TAG, "parseResult: " + jsonObj);
for (int i = 0; i < jsonObj.length(); i++) {
// if (response != null) {
String images = jsonObj.getString("images");
item.setImage(IMAGE_LINK + images);//IMAGE_LINK +
Log.i(TAG, "parseResult: " + IMAGE_LINK + " " + images);
mGridData.add(item);
}
} catch (JSONException e1) {
e1.printStackTrace();
}
}
return null;
}
dose i retrieve data correctly ?
Is images json object string or json array? In your code is string.
If WebService changes are possible, request to given you a json array of images, this is best practice.
If not possible you must parse json image object with regex.
No your doing wrong just try below code
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray arrayObj = jsonObj.getJSONArray("images");
for(int i=0;i<arrayObj.length();i++)
{
String item = arrayObj.getString(i);
// now you use item string where you want
}
} catch (JSONException e) {
e.printStackTrace();
}
images should be a JSONArray, and hence you can do that to parse it (inside your for loop!):
JSONArray imagesJSON = jsonObj.getJSONArray("images");
for(int k = 0 ; k<imagesJSON.length() ; k++){
String image = imagesJSON.getString(k);
item.setImage(IMAGE_LINK + image);//IMAGE_LINK +
Log.i(TAG, "parseResult: " + IMAGE_LINK + " " + image);
mGridData.add(item);
}
I'trying to Parsing JSOn object but sometime it runs properly sometime getting followoing error:
org.json.JSONException: Value null at VesselList of type
org.json.JSONObject$1 cannot be converted to JSONArray
public void getCompanyDeatails()
{
String strUrl_companyDeatls = "http://103.24.4.60/CLASSNK1/MobileService.svc/Get_Company/Sync_Time/"+strSync_Time+"/Authentication_Token/"+str_Authentication_Token;
Log.e("strUrl_companyDeatls ", " = " + strUrl_companyDeatls);
InputStream inputStream = null;
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpResponse httpResponse = httpclient.execute(new HttpGet(strUrl_companyDeatls));
inputStream = httpResponse.getEntity().getContent();
if (inputStream != null)
strResult = convertInputStreamToString(inputStream);
else
strResult = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
String jsonStr = strResult;
Log.e("jsonStr ", " = " + jsonStr);
if (jsonStr != null)
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String jsonResult = jsonObj.toString().trim();
Log.e("jsonResult ", " = " + jsonResult);
JSONObject companyList = jsonObj.getJSONObject("Get_CompanyResult");
Log.e("companyList ", " = " + companyList.toString());
JSONArray jarr = jsonObj.getJSONArray("CompanylList");
Log.e("jarr ", " = " + jarr.toString());
for (int i = 0; i < jarr.length(); i++) {
JSONObject jobCompanyDetails = jarr.getJSONObject(i);
str_CompanyId = jobCompanyDetails.getString("Company_ID");
str_CompanyName = jobCompanyDetails.getString("Company_Name");
Log.e("str_CompanyId ", " = " + str_CompanyId);
Log.e("str_CompanyName ", " = " + str_CompanyName);
if (dbhelper.isTitleExist(str_CompanyId)) {
//Upadte
dbhelper.updatedetails(str_CompanyId, str_CompanyName);
Log.e("Data updated in ", "Company Table !!");
} else {
//insert
dbhelper.insertCompany(str_CompanyId, str_CompanyName);
Log.e("Data inserted in ", "Company Table !!");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
this is my JSON String
{"Get_CompanyResult":{"CompanylList":[{"Company_ID":93,"Company_Name":"SeaChange"},{"Company_ID":97,"Company_Name":"VM 2"}],"Sync_Time":"2015-09-11 12:44:17.533"}}
Is this code is right?
Here:
JSONArray jarr = jsonObj.getJSONArray("CompanylList");
line causing issue because CompanylList JSONArray is inside Get_CompanyResult JSONObject instead of main which is jsonObj.
Get CompanylList JSONArray from companyList JSONObject:
JSONArray jarr = companyList.getJSONArray("CompanylList");
Change your code according to here :
public void getCompanyDeatails() {
String strUrl_companyDeatls = "http://103.24.4.60/CLASSNK1/MobileService.svc/Get_Company/Sync_Time/" + strSync_Time + "/Authentication_Token/" + str_Authentication_Token;
Log.e("strUrl_companyDeatls ", " = " + strUrl_companyDeatls);
InputStream inputStream = null;
String strResult = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse httpResponse = httpclient.execute(new HttpGet("strUrl_companyDeatls"));
inputStream = httpResponse.getEntity().getContent();
// strResult = "{\\\"Get_CompanyResult\\\":{\\\"CompanylList\\\":[{\\\"Company_ID\\\":93,\\\"Company_Name\\\":\\\"SeaChange\\\"},{\\\"Company_ID\\\":97,\\\"Company_Name\\\":\\\"VM 2\\\"}],\\\"Sync_Time\\\":\\\"2015-09-11 12:44:17.533\\\"}}";
String jsonStr=null;
if (inputStream != null) {
strResult = convertInputStreamToString(inputStream);
jsonStr = strResult;
}
Log.e("jsonStr ", " = " + jsonStr);
if (jsonStr != null) {
JSONObject jsonObj = new JSONObject(jsonStr);
String jsonResult = jsonObj.toString().trim();
Log.e("jsonResult ", " = " + jsonResult);
JSONObject companyList = jsonObj.getJSONObject("Get_CompanyResult");
Log.e("companyList ", " = " + companyList.toString());
JSONArray jarr = companyList.getJSONArray("CompanylList");
Log.e("jarr ", " = " + jarr.toString()); // error was here. You need to use companyList json object because it contains company list.
for (int i = 0; i < jarr.length(); i++) {
JSONObject jobCompanyDetails = jarr.getJSONObject(i);
String str_CompanyId = jobCompanyDetails.getString("Company_ID");
String str_CompanyName = jobCompanyDetails.getString("Company_Name");
Log.e("str_CompanyId ", " = " + str_CompanyId);
Log.e("str_CompanyName ", " = " + str_CompanyName);
// if (dbhelper.isTitleExist(str_CompanyId)) {
// //Upadte
// dbhelper.updatedetails(str_CompanyId, str_CompanyName);
// Log.e("Data updated in ", "Company Table !!");
// } else {
//
// //insert
// dbhelper.insertCompany(str_CompanyId, str_CompanyName);
// Log.e("Data inserted in ", "Company Table !!");
// }
}
}
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
}
Note :
There is no need to use nested try and catch.
For 'strResult = "Did not work!";', always make sure that every
exception handled well (at checkpoint of jsonstr is null or not you
can not identify error occurred at parsing input stream can lead to
serious bugs).
HttpClient is deprecated so make sure you use latest version of any
third party library like Volley or Retrofit for network
operation and GSON for parsing response. It will minimize your
efforts.
Thanks.
I am a little new to android/java. I am trying to pass JSON values into a list and then into a multidimensional array. I am not having much success.
2 questions,
1) How would I load all of the variables in a json array into children[][]?
2) How do you view children[][] in Log.i
Herei s my code:
List<String> cList = new ArrayList<String>();
String customer_name, customer_title, customer_postal_code, customer_city, customer_state, customer_street_address;
ArrayList<String> cTitle, cClubName, cPostalCode, cCity, cState, cStreet = new ArrayList<String>();
public String[][] children = null;
//... onCreate method, HTTP Connection, StringBuilder, etc. These work fine...
// Pass data into array
try{
JSONArray jArray = new JSONArray(result);
JSONObject jData=null;
String[][] children = new String[jArray.length()][6];
for(int i=0;i<jArray.length();i++){
jData = jArray.getJSONObject(i);
customer_name=jData.getString("customer_name");
Log.i("JSON ", "customer_name LOG " + customer_name);
cList.add(customer_name);
customer_title=jData.getString("event_title");
Log.i("JSON ", "customer_title LOG " + customer_title);
cList.add(customer_title);
customer_street_address=jData.getString("customer_street_address");
Log.i("JSON ", "customer_Id LOG " + customer_street_address);
cList.add(customer_street_address);
customer_city=jData.getString("customer_city");
Log.i("JSON ", "customer_city LOG " + customer_city);
cList.add(customer_city);
customer_state=jData.getString("customer_state");
Log.i("JSON ", "customer_state LOG " + customer_state);
cList.add(customer_state);
customer_postal_code=jData.getString("customer_postal_code");
Log.i("JSON ", "customer_postal_code LOG " + customer_postal_code);
cList.add(customer_postal_code);
for(int ic = 0; ic < cList.size(); ic++) {
Log.i("jData ", "length " + jData.length());
children[i][ic] = (String) cList.get(ic);
}
Log.i("Child Array", "Children array LOG " + children);
}
}catch(JSONException e1){
Toast.makeText(getBaseContext(), "No customers Found", Toast.LENGTH_LONG).show();
}catch (ParseException e1){
e1.printStackTrace();
}
}
If I understood your code correctly you don't need cList.
Something like that should do the work
String[][] children = new String[jArray.length()][6];
for(int i=0;i<jArray.length();i++){
jData = jArray.getJSONObject(i);
customer_name=jData.getString("customer_name");
Log.i("JSON ", "customer_name LOG " + customer_name);
children[i][0] = customer_name;
customer_title=jData.getString("event_title");
Log.i("JSON ", "customer_title LOG " + customer_title);
children[i][1] = event_title;
customer_street_address=jData.getString("customer_street_address");
Log.i("JSON ", "customer_Id LOG " + customer_street_address);
children[i][2] = customer_street_address;
customer_city=jData.getString("customer_city");
Log.i("JSON ", "customer_city LOG " + customer_city);
children[i][3] = customer_city;
customer_state=jData.getString("customer_state");
Log.i("JSON ", "customer_state LOG " + customer_state);
children[i][4] = customer_state;
customer_postal_code=jData.getString("customer_postal_code");
Log.i("JSON ", "customer_postal_code LOG " + customer_postal_code);
children[i][5] = customer_postal_code;
}
Make sure your JSON data is well-formed to avoid exceptions.
To view children[][] you can just iterate twice on your multidimentional array and do Log.i("MyTag", "Value: " + children[i][j]);
String[][] data = new String[jsonArray.length][];
for(int i = 0; i<jsonArray.length; i++){
data[i] = ((ArrayList)jsonArray).get(i).toArray(new String[((ArrayList)jsonArray).get(i).size])
}
for printing in log
Log.d("array", data);