org.json.JSONException: No value for price - java

I get result json and parse in android. Exception has happened with a message: org.json.JSONException: No value for price
W/System.err: org.json.JSONException: No value for price
W/System.err: at org.json.JSONObject.get(JSONObject.java:389)
W/System.err: at org.json.JSONObject.getString(JSONObject.java:550)
My java class
JSONParser jsonParser = new JSONParser();
// tracks JSONArray
JSONArray albums = null;
// Album id
String album_id = null;
String song_id = null;
String album_name, song_name, price;
// single song JSON url
// GET parameters album, song
private static final String URL_SONG = "my url";
// ALL JSON node names
private static final String TAG_NAME = "name";
private static final String TAG_PRICE = "price";
private static final String TAG_ALBUM = "name"; // album
...
try {
JSONObject jObj = new JSONObject(json);
if(jObj != null){
song_name = jObj.getString(TAG_NAME);
album_name = jObj.getString(TAG_ALBUM);
price = jObj.getString(TAG_PRICE);
}
}
catch (JSONException e) {
e.printStackTrace();
}
My json URL:
{
"id": "551"
"name": "Rent Disk"
"price": "3233333"
"album_id": "3"
"album": "Michael"
}
How to fix this exception? thank so much !!

You can put a check like this before putting value
JSONObject jObj = new JSONObject(json);
if(jObj != null) {
if(jObj.has(TAG_NAME)) {
song_name = jObj.getString(TAG_NAME);
}
if(jObj.has(TAG_ALBUM)){
album_name = jObj.getString(TAG_ALBUM);
}
if(jObj.has(TAG_PRICE)){
price = jObj.getString(TAG_PRICE);
}
}

JSONException
Thrown to indicate a problem with the JSON API
FYI
{
"id": "551"
"name": "Rent Disk"
"price": "3233333"
"album_id": "3"
"album": "Michael"
}
Post your Json Here
If above is your json then it is not valid .
For your requirement you should use JSONObject .has("") and .isNull("") method .
Edited
Your perfect Json is
{ "id": 551, "name": "Cho thue xe Toyota5", "price": "3233333", "album_id": "3", "album": "Huyndai" }
Try with this
JSONObject myJson = new JSONObject(json);
String getName = myJson.optString("name");
int getID= myJson.optInt("id");

Related

Unable to extract jsonarray from jsonobject

I have been battling with response from server using retrofit.
I have this json response from server
{
"success": true,
"message": "Your Requests",
"data": {
"requests": [
{
"_id": "5d163a5ed2399f8be6d8d867",
"created": "2019-06-28T16:03:42.463Z",
"pickupCoordinates": [
8.0099,
6.0909
],
"destinationCoordinates": [
9.088788,
3.099403
],
"customerName": "Seun Akinbode",
"pickupAddress": "Lekki",
"destinationAddress": "Ajah",
"accessCode": "3334",
"busPlate": "DD222RR",
"flaName": "Simi",
"flaEmail": "awele#kobo360.com",
"__v": 0
} ]
}
I use below class to parse the json but unfortunately, it couldn't extract the array requests into jsonArray
public ArrayList<RequestModel> getData(String response)
{
Log.d("responseData :", response);
ArrayList<RequestModel> dataList = new ArrayList<>();
try {
JSONObject mainObj = new JSONObject(response);
JSONArray array = mainObj.getJSONArray("data");
Log.d("The main Array :", array.toString());
RequestModel data;
for(int i = 0;i<array.length();i++)
{
data = new RequestModel();
JSONObject resObj = array.getJSONObject(i);
JSONArray reqArray = resObj.getJSONArray("requests");
for( int j =0;j<reqArray.length();j++) {
JSONObject reqObj = reqArray.getJSONObject(j);
data.setAccessCode(reqObj.getString("accessCode"));
Log.d("Accessecode :", reqObj.getString("accessCode"));
data.setCustomerName(reqObj.getString("customerName"));
Log.d("customerName :", reqObj.getString("customerName"));
}
dataList.add(data);
}
} catch (Exception e) {
e.printStackTrace();
}
return dataList;
}
Logcat is printing the JSONObject but it says at ... data of type org.json.JSONObject cannot be converted to JSONArray
You are trying to extract an array from the data field, while the response contains an object. Perhaps you meant to get the object data, then the array requests from within it.
This could be the problem:
JSONArray array = mainObj.getJSONArray("data");
data is an object as seen in the response, not an array.

How to parse login response in android?

I am confused about parsing so I want to know about how to parse. Whenever I login with valid login id and password give response
{
"data": {
"status": "1",
"Full Name": [
{
"user_id": 1,
"user_name": "deepika#soms.in",
"full_name": "",
"display_name": "",
"token": "",
"photo_url": "http://clients.vfactor.in/putt2gether/images/profile/default.jpg"
}
],
"Event": [
{
"latest_event_id": "",
"format_id": ""
}
],
"msg": "Success Login"
}
}
and if invalid login id then give response
{
"Error": {
"msg": "Please Enter valid Email Address"
}
try {
JSONObject obj = new JSONObject(response);
if (obj.has("Error")) {
JSONObject objError = obj.getJSONObject("Error");
} else if (obj.has("data")) {
JSONObject objData = obj.getJSONObject("data");
}
} catch (Exception e) {
e.printStackTrace();
}
You need to parse the json answer.
There are many sources to learn how to do that:
Oracle documentation
Jackson documentation - Jackson is a library to parse json
GSon documentation - Another json parser
Let's assume response be,
String response;
try
{
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.has("data"))
{
JSONObject jsonObjData = jsonObject.getJSONObject("data");
String status = jsonObject.getString("status");
JSONArray jsonArrayName = jsonObjData.getJSONArray("Full Name");
for (int i = 0; i < jsonArrayName.length(); i++) {
JSONObject jsonObj = jsonArrayName.getJSONObject(i);
Integer user_id = jsonObj.getInt("user_id");
String user_name = jsonObj.getString("user_name");
String full_name = jsonObj.getString("full_name");
String display_name = jsonObj.getString("display_name");
String photo_url = jsonObj.getString("photo_url");
}
JSONArray jsonArrayEvent = jsonObjData.getJSONArray("Event");
for (int i = 0; i < jsonArrayEvent.length(); i++) {
JSONObject jsonObj = jsonArrayEvent.getJSONObject(i);
String latest_event_id = jsonObj.getString("latest_event_id");
String format_id = jsonObj.getString("format_id");
}
String msg = jsonObject.getString("msg");
} else if (jsonObject.has("Error")) {
JSONObject jsonObjError = jsonObject.getJSONObject("Error");
String msg = jsonObjError.getString("msg");
}
} catch (Exception e) {
e.printStackTrace();
}

Issues with JSON Parsing Android

I have Json like this:
{
"id": 226112,
"name": "name",
"min": 1,
"km": "0.33",
"url": "5___2_2.htm",
"departures": [
{
"type": "DATA",
"departures": {
"5": [
"04",
"19",
"34",
"47",
"59"
],
"6": [
"11",
"23",
"35",
"47",
"59"
]
etc..
And I try to parse it:
private static final String TAG_DEPARTURES = "departures";
private static final String TAG_TYPE = "type";
private static final String TAG_DEPARTURES2 = "departures";
private static String TAG_HOUR = "5";
...
example
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
timetables = jsonObj.getJSONArray(TAG_DEPARTURES);
for (int i = 0; i < timetables.length(); i++) {
JSONObject c = timetables.getJSONObject(i);
String type = c.getString(TAG_TYPE);
JSONObject departures = c.getJSONObject(TAG_DEPARTURES2);
String hour = departures.getString(TAG_HOUR);
HashMap<String, String> timetable = new HashMap<String, String>();
timetable.put(TAG_TYPE, type);
timetable.put(TAG_DEPARTURES2, hour);
timetableList.add(timetable);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
...
Finally I get this:
DATA ["04","19","34","47","59"]
And this is String
["04","19","34","47","59"]
I would like to get String[] tab, where:
tab[0] = "04";
tab[1] = "19";
...
I think your json returned is not like you want.maybe you want an array for the key:5,6,but your json showed in question is just a string,so if you can control the json returned by server,please change its format to an string array.
If you can't control the json returned,you should extract the real string by yourself.Like this:
public String[] extractArray(final String str){
final String strNoBrace = str.substring(1,str.length()-1);
String[] tempResult = strNoBrace.split(",");
if(tempResult==null) return null;
String[] result = new String[tempResult.size()];
for(int i=0,size=tempResult.size();i<size;++i){
String temp = tempResult[i];
result[i] = temp.substring(1,temp.length()-1);
}
return result;
}

How to parse the json object with multiple keys in android

I want to put the JSON result in textviews but because of multiple array i can get only one key/value of datetime, location and status objects. The json object is:
{
"signature":"testSignature",
"deliverydate":"2015-08-06 15:07:00",
"datetime":{
"0":1438848420,
"1":1438841820,
"2":1438838760,
},
"location":{
"0":"PA",
"1":"PA",
"2":"PA",
},
"status":{
"0":"packed",
"1":"On the go",
"2":"delivered",
},
"pickupdate":2015-08-04 07:55:00
}
and this is my java code:
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("NO", NUMBER_TO_POST));
JSONObject json = jsonParser.makeHttpRequest(URL_TO_POST, "POST", params);
success = json.getString(TAG_SIGNATURE);
if (success != null) {
SIGNATURE = json.getString(TAG_SIGNATURE);
DELIVERY_DATE = json.getString(TAG_DELIVERY_DATE);
JSONObject DT = json.getJSONObject(TAG_DATETIME);
DATETIME = DT.getString("0");
JSONObject LOC = json.getJSONObject(TAG_LOCATION);
LOCATION = LOC.getString("0");
JSONObject STAT = json.getJSONObject(TAG_STATUS);
STATUS = STAT.getString("0");
PICKUP_DATE = json.getString(TAG_PICKUP_DATE);
}else{
finish();
}
} catch (JSONException e) {
e.printStackTrace();
}
can anyone help me to solve this? Thanks
You should use GSON library to parse JSONs.
And to be a bit more helpful, here is how your class to hold JSON values might look like:
class MyClassForGsonToHoldParseJSON {
String signature;
String deliverydate;
Map<String, long> datetime;
Map<String, String> location;
Map<String, String> status;
String pickupdate;
}
Then just use something like this to conver variable json with JSON data to an object:
Gson gson = new Gson();
MyClassForGsonToHoldParseJSON f = gson.fromJson(json, MyClassForGsonToHoldParseJSON.class);
Your JSON format is wrong:
{
"signature": "testSignature",
"deliverydate": "2015-08-06 15:07:00",
"datetime": {
"0": 1438848420,
"1": 1438841820,
"2": 1438838760
},
"location": {
"0": "PA",
"1": "PA",
"2": "PA"
},
"status": {
"0": "packed",
"1": "On the go",
"2": "delivered"
},
"pickupdate": " 2015-08-04 07:55:00"
}

How to parse this type of JSON in Java?

How do I fetch the third leaveTypeId and year from leaveInfo?
{
"statusCode":"1001",
"message":"Success",
"response":{
"leaveInfo":[
{
"leaveTypeId":1,
"year":2014
},
{
"leaveTypeId":2,
"year":2014
},
{
"leaveTypeId":3,
"year":2014,
},
{
"leaveTypeId":4,
"year":2014
},
{
"leaveTypeId":5,
"year":2014
},
{
"leaveTypeId":6,
"year":2014
}
]
}
}
I did this to achieve my need
JSONObject jobj1 = new JSONObject(result);
String statusCode = jobj1.getString("statusCode");
if (statusCode.equalsIgnoreCase("1001"))
{
String response = jobj1.getString("response");
JSONObject jobj2 = new JSONObject(response);
String leaveInfo = jobj2.getString("leaveInfo");
System.out.println("leaveInfo: "+leaveInfo);
}
I don't know how to go further as there are no key values for the arrays inside leaveInfo. Please help me in this regard.
Use this
JSONObject jobj1 = new JSONObject(result);
String statusCode = jobj1.getString("statusCode");
if (statusCode.equalsIgnoreCase("1001"))
{
String response = jobj1.getString("response");
JSONObject jobj2 = new JSONObject(response);
JSONArray ary=jobj2.getJSONArray("leaveInfo");
for(int i=0;i<ary.length;i++){
JSONObject obj=ary.getJSONObject(i);
String leaveInfo=obj.getString("leaveTypeId");
System.out.println("leaveInfo: "+leaveInfo);
}
}
I hope this will help to you :)

Categories

Resources