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);
}
Related
I'm using volley to get json object, I'm getting data like this
{"resultUser":19}
{"resultUser2":13}
How to get either the second one (resultuser2) or both?
try {
JSONObject o = new JSONObject(response);
String data = (String) o.get("resultUser2");
if (!data.equals("")) {
Toast.makeText(getApplicationContext(), "user2 id" + data, Toast.LENGTH_LONG).show();
//UserDetailsActivty.this.finish();
} else {
Toast.makeText(getApplicationContext(), "Ohh! Sorry,,Signing Up Failed ", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
you can use JsonArray to iterate through all the jsonobjects like this
try {
JSONArray jsonArray = new JSONArray(response);
for (int i =0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.get(i);
//do whatever you want to do with the data
}
} catch(Exception e) {
}
I have a json object as below
{
"Book1":{"Title1":"Cost1","Title2":"Cost2"},
"Book2":{"Title3 ":"Cost3"},
"Book3":{"Title4 ":"Cost4","Title5 ":"Cost5"},
"Book4":{"Title6":"Cost6","Title7”:”Cost7","Title8”:”Cost8"}
}
I want to retrieve all the values of "Titles" without any keywords i.e I would like to have {Title1,Title2,Title3,Title4,...} in an array.
Below is my code to retrieve based on Book name but now I need to retrieve all the values
List<String> books=new ArrayList<String >();
try {
JSONObject obj = new JSONObject(loadJSONFromAssetArea());
JSONObject bookJson = obj.getJSONObject("Book1");
Iterator<String> keys= bookJson.keys();
do
{
String keyValue = (String)keys.next();
JSONArray specTitle = obj.getJSONArray(keyValue);
for (int i = 0; i < specTitle.length(); i++) {
books.add(specTitle.get(i).toString());
}
}while(keys.hasNext());
} catch (JSONException e) {
e.printStackTrace();
}
I am not getting how to get with out passing key values to json object .
Kindly help.
Thanks in advance
Try This is Working
JSONObject jsonObject = new JSONObject(loadJSONFromAssetArea());
List<String> books=new ArrayList<String >();
try {
Iterator iteratorObj = jsonObject.keys();
while (iteratorObj.hasNext())
{
String getJsonObj = (String)iteratorObj.next();
System.out.println("Book No.: " + "------>" + getJsonObj);
JSONObject jo_inside = jsonObject.getJSONObject(getJsonObj);
//JSONObject jo_inside = new JSONObject((String) iteratorObj.next());
Iterator<String> keys = jo_inside.keys();
while (keys.hasNext())
{
String key = keys.next();
String value = jo_inside.getString(key);
Log.v("Book Title key", key);
Log.v("Book Name value", value);
books.add(jo_inside.getString(key));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
NOTE
Your GIVEN Json is not Valid.
Book1,Book2.. are DYNAMIC/UNKNOWN.
Use Iterator in this way.
Try this way,
JSONObject jOBJ= new JSONObject(loadJSONFromAssetArea());
Iterator iteratorObj = jOBJ.keys();
while (iteratorObj.hasNext())
{
String getJsonObj = (String)iteratorObj.next();
System.out.println("Key: " + Key + "------>" + getJsonObj); // print Book1,Book2..
// Now your work
}
If you want to parse this
{
"Book1":{"Title1":"Cost1","Title2":"Cost2"},
"Book2":{"Title3 ":"Cost3"},
"Book3":{"Title4 ":"Cost4","Title5 ":"Cost5"},
"Book4":{"Title6":"Cost6","Title7”:”Cost7","Title8”:”Cost8"}
}
you can use this code to parse the json object,
List<String> books = new ArrayList<String>();
try {
JSONObject obj = new JSONObject(loadJSONFromAssetArea());
JSONObject bookJson, innerObject;
Iterator<String> keys = obj.keys();
do {
String keyValue = (String) keys.next();
if (obj.get(keyValue) instanceof JSONObject) {
bookJson = obj.getJSONObject(keyValue);
Iterator<?> innerKeys = bookJson.keys();
while (innerKeys.hasNext()) {
String innerKey = (String) innerKeys.next();
innerObject = bookJson.getJSONObject(innerKey);
books.add(innerObject.getString(innerKey));
}
}
} while (keys.hasNext());
} catch (JSONException e) {
e.printStackTrace();
}
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 am trying to get the user details using people.get in which I have emails which I need to get that value.
This is what I mean:
This is how I'm trying to do but unable to get the value
try {
String resp =profile.getEmails().toString();
JSONObject mainObject = new JSONObject(resp);
JSONObject uniObject = mainObject.getJSONObject("emails");
String email = uniObject.getString("value");
((TextView) findViewById(R.id.txtemail)).setText(email);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Any help is appreciated.
In your JSON response, emails is a JSONArray, not a JSONObject. You would need to get it like this:
JSONObject json= new JSONObject(responseString); //your response
try {
JSONArray responseArray = jsonObj.getJSONArray("email");
for (int i = 0; i < responseArray.length(); i++) {
// get value with the NODE key
JSONObject obj = responseArray.getJSONObject(i);
String lastName = obj.getString("value");
String firstName = obj.getString("type");
EmailResponse myResp = new EmailResponse();
myResp.setValue(value);
myResp.setType(type);
//set all other Strings
//lastly add this object to ArrayList<MyResponse> So you can access all data after saving
}
}
catch (JSONException e) {
e.printStackTrace();
}
POJO Class:
public class EmailResponse{
public String value = "";
public String type = "";
//getter setters
}
Hope this helps.
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);
}