I want to parse following JSON
{
"fail": true,
"errors": {
"arrival_date": ["The arrival date should be greater than or equal to departure date !!!"]
}
}
I want to get value of The arrival date should be greater than or equal to departure date !!!
I tried this code but not getting success
try {
org.json.JSONObject jsonObj = new org.json.JSONObject(PostParseGet.mStringresponse);
org.json.JSONObject c = jsonObj.getJSONObject("errors");
JSONArray contacts = c.getJSONArray("arrival_date");
Log.d("Errors",contacts.get(0).toString());
} catch (JSONException e) {
e.printStackTrace();
}
Any idea how can I get this value?
String data ="{ 'fail': 'true', 'errors': { 'arrival_date': ['The arrival date should be greater than or equal to departure date !!!']}}";
try {
JSONObject object = new JSONObject(data);
JSONObject error = object.getJSONObject("errors");
JSONArray array = error.getJSONArray("arrival_date");
String dataString = array.getString(0);
String dat = dataString;
}
catch(Exception e) {
e.printStackTrace();
}
Try below Code
try {
JSONObject jObject=new JSONObject(PostParseGet.mStringresponse);
JSONObject errorObject=jObject.optJSONObject("errors");
JSONArray arraiValArray=errorObject.optJSONArray("arrival_date");
if(arraiValArray.length()>0)
{
for (int i = 0; i < arraiValArray.length(); i++) {
Log.i("TAG", "String:"+arraiValArray.optString(i));
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Related
I'm new to Android and I have tried so many options to access the JSONObject which returns from an API call but I couldn't succeed as any of the solutions i looked for didn't work for me.
What i want is to access the JSONObject and keep the Id & Name in a Array. And then populate the Names in a AutoCompleteTextView. How do i properly access the JSONObject. Please help me with this. I'm stuck on this for more than a day.
Following is my Code handling the JSONObject.
#Override
public void processFinish(JSONObject output) {
Toast.makeText(MainActivity.this,"ProcessFinish",Toast.LENGTH_SHORT).show();
allStations = output;
if(output != null){
Toast.makeText(MainActivity.this,output.toString(),Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(MainActivity.this," Connection Failed!",Toast.LENGTH_SHORT).show();
}
}
Following is a sample output of my JSONObject
{
"SUCCESS": true,
"MESSAGE": "Found 398 Results!",
"NOFRESULTS": 3,
"RESULTS": {
"stationList": [
{
"stationCode": "ABN",
"stationID": 3,
"stationName": "ABLA"
},
{
"stationCode": "ADLA",
"stationID": 410,
"stationName": "ADLA"
},
{
"stationCode": "ANM",
"stationID": 11,
"stationName": "AHAMA"
}]
},
"STATUSCODE": "2000"
}
try this
try {
JSONObject obj= output.getJSONObject("RESULTS");
JSONArray dataArray= obj.getJSONArray(“stationList“);
for(int i=0;i<dataArray.length();i++)
{
JSONObject object1=dataArray.getJSONObject(i);
Strind id = object1.getString("stationID");
}
} catch (JSONException e) {
e.printStackTrace();
}
In This code output is your JSONObject result
try this
try {
JSONObject jsonObject = new JSONObject("response");
boolean status= jsonObject.getBoolean("SUCCESS");
String MESSAGE= jsonObject.getString("MESSAGE");
String NOFRESULTS= jsonObject.getString("NOFRESULTS");
String STATUSCODE= jsonObject.getString("STATUSCODE");
JSONObject obj=jsonObject.getJSONObject("RESULTS");
JSONArray jsonarray = obj.optJSONArray("stationList");
for (int i = 0; i < jsonarray.length(); i++){
JSONObject json_data = jsonarray.getJSONObject(i);
Log.e("stationCode",json_data.getString("stationCode"));
Log.e("stationID",json_data.getString("stationID"));
Log.e("stationName",json_data.getString("stationName"));
}
} catch (JSONException e) {
e.printStackTrace();
}
Have you tried using a JSON Array? For example you could use this method for storage:
JSONObject wgroup = new JSONObject(); //FINAL json object
try { //put initial data
wgroup.put("id", "2");
wgroup.put("user", "someone");
wgroup.put("stime", "2017-02-06 16:30:13");
wgroup.put("etime", "2017-02-06 19:30:13");
wgroup.put("real_dur", 3600);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONArray jsonArray1 = new JSONArray(); //Create an array to store ALL Variables
for (int y=0; y< your_array.length ; y++ ){ //loop through your information array
JSONObject output = new JSONObject(); //CREATE a json object to put 1 workout
try {
wgroup.put("id", "2");
wgroup.put("name", "sam");
wgroup.put("age", "3");
wgroup.put("gender", "male");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONArray jsonArray2 = new JSONArray(); //CREATE a json array to put 1 array
jsonArray1.put(output); //insert this OBJECT into the ARRAY
}
wgroup.put(jsonArray1);//insert the workouts ARRAY into the original object
I have a dynamic JSON string that looks like this:
{"_id":"7","food_name":"Fiber Balance"},{"_id":"8","food_name":"Sport +"}
I am able to get the first name, but not the second one. This is my code for getting the first (Fiber Balance):
// Dynamic text
TextView textViewDynamicText = (TextView)getActivity().findViewById(R.id.textViewDynamicText);
String stringJSON = textViewDynamicText.getText().toString();
String stringFoodname = "";
try {
JSONObject jsonObject = new JSONObject(stringJSON);
Iterator<String> iter = jsonObject.keys();
while (iter.hasNext()) {
String key = iter.next();
try {
stringFoodname = jsonObject.getString("food_name");
Toast.makeText(getContext(), stringFoodname, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
// Something went wrong!
}
}
} catch (org.json.JSONException e) {
// Something went wrong!
}
How can I go to the next item in the json string?
If you have multiple data than you need to use Array,if you want to get all data from your json use below trick,
String json = "{\"_id\":\"7\",\"food_name\":\"Fiber Balance\"},{\"_id\":\"8\",\"food_name\":\"Sport +\"}";
json = "[" + json + "]";
try {
JSONArray array = new JSONArray(json);
for (int i = 0; i < array.length(); i++) {
JSONObject object = array.getJSONObject(i);
String foodName = object.getString("food_name");
Log.e("FoodName:", foodName);
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("error", "json", e);
}
I want to get the id ^& content value in http://rest-service.guides.spring.io/greeting
What i tried is,
try {
JSONObject jsonObj = new JSONObject(parsingUrl);
// If you have array
JSONArray resultArray = jsonObj.getJSONArray("id"); // Here you will get the Array
// Iterate the loop
for (int i = 0; i < resultArray.length(); i++) {
// get value with the NODE key
JSONObject obj = resultArray.getJSONObject(i);
String name = obj.getString("content");
}
// If you have object
//String result1 = jsonObj.getString("result");
} catch (Exception e) {
e.printStackTrace();
}
Thanks
The url that your mentioned dont have json arrays, parsing will be like
try {
JSONObject jsonObj = new JSONObject(resultfromUrl);
int id = jsonObj.getInt("id");
String name = jsonObj.getString("content");
} catch (JSONException e) {
e.printStackTrace();
}
I have a JSON data which is accessible through a link like http://192.55.23.210:8085/Services/getFriends?userId=xyz which returns an array like ["xyz","abc"]. How to access these objects
You can get the field names without having to know them using names(int) method of JSONObject class, and then access them:
public void getFieldNames(JSONArray jsonArray) {
List<String> fieldNames = new ArrayList<String>;
try {
for (int i = 0; i < jsonArray.length(); ++i) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
fieldNames[i] = jsonObject.names(i);
}
} catch (Exception e) {
Log.e("ConnectToDatabase->getJsonData", "Error Parsing JSON Data "
+ e.toString());
}
}
JSONParser parser=new JSONParser();
String s="[\"xyz\",\"abc\"]";
try {
JSONArray jsonarray=(JSONArray)parser.parse(s);
for (Object object : jsonarray) {
System.out.println((String)object);
}
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Sending and Parsing JSON in Android
I have a JSON result in the following format which JSON Lint shows this as a Valid Response.
My question is: how do I accesss the content of "reportId0" value "164", "reportId1" value 157,reportId2 value 165, etc are all dynamic values?
My sample code for accessing value of properties.How to get Value reportid And add allvalue in Arraylist?
"properties": {
"link": "",
"approvalsReportCount": 3,
"reportName0": "srcapprovals",
"reportId0": 164,
"reportName1": "Approvals",
"reportId1": 157,
"requests_report_id": "163",
"requests_report_name": "EG approvals",
"reportName2": "fulfillment",
"reportId2": 165
}
This is the best way i found it to get ReportId value.
Below is My code
JSONObject jObj = new JSONObject(result);
JSONObject jsonResultArray = jObj.getJSONObject("results");
JSONObject pro_object = jsonResultArray.getJSONObject("properties");
Iterator keys = pro_object.keys();
while(keys.hasNext()) {
String currentDynamicKey = (String)keys.next();
String value = pro_object.getString(currentDynamicKey);
String upToEightCharacters = currentDynamicKey.substring(0, Math.min(currentDynamicKey.length(), 8));
if(upToEightCharacters.startsWith("reportId"))
{
Log.v("key"," new report ID key " + currentDynamicKey);
Log.v("key"," new report ID key " + pro_object.getString(currentDynamicKey) );
}
}
you can use this
public ArrayList<String> getReportIds() {
boolean isContinue = true;
JSONObject json;
String tag = "reportId";
int i = 0;
ArrayList<String> repIdList = new ArrayList<String>();
JSONObject prop = null;
try {
json = new JSONObject("<your json string>");
prop = json.getJSONObject("properties");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while (isContinue) {
String repId = "";
try {
repId = prop.getString(tag + i);
repIdList.add(repId);
i++;
} catch (JSONException e) {
isContinue = false;
e.printStackTrace();
}
}
return repIdList;
}
You can Try This!!
try {
JSONObject jObj = new JSONObject(result);
JSONObject jsonResultArray = jObj.getJSONObject("results");
Log.v("log_tag","json result Array : "+ jsonResultArray);
JSONObject pro_object = jsonResultArray.getJSONObject("properties");
Iterator keys = pro_object.keys();
while(keys.hasNext()) {
// loop to get the dynamic key
String currentDynamicKey = (String)keys.next();
String value = pro_object.getString(currentDynamicKey);
approvaldto_Key = new All_Approval_Key_dto();
String upToEightCharacters = currentDynamicKey.substring(0, Math.min(currentDynamicKey.length(), 8));
if(upToEightCharacters.startsWith("reportId"))
{
approvaldto_Key.requestId = pro_object.getString(currentDynamicKey);
fetchrecursUserData.add(approvaldto_Key);
}
}
}
catch (JSONException e) {
e.printStackTrace();
}
return fetchrecursUserData;
}
You can try below code
String serial= jsonObject.getJSONObject("response").getString("serialNumber");
or
JSONObject json;
try {
json = new JSONObject(buffer.toString());
String accessToken = json.getString("access_token");
return accessToken;
} catch (JSONException e) {
Log.e("Podcast", "There was an error", e);
}