Retrieving all values of json object into array list - android

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();
}

Related

Json move to next item

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);
}

Regd : getting value from json url

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();
}

Save json to array key-value in android

I have a problem with json.
I get this response from server:
{"TESTS":true,"TESTS_VIEW":true,"ORDER":true,"PARAMETERS":true,"VIEW":true}
How can I save this data in array or something else to have schema: key - value?
Hmm, not sure I understand why you want this. A JSONObject gives you exactly that, have a look at JSONObject.get():
JSONObject json = new JSONObject(yourjsonstringfromserver);
boolean tests = json.getBoolean("TESTS");
Still, if you want to iterate over all values you can do like this:
Map<String, Object> map = new HashMap<String, Object>();
Iterator<String> keys = json.keys();
for(String key : keys) {
try {
Object value = json.get(key);
map.put(key, value);
}
catch (JSONException e) {
// Something went wrong!
}
}
JSONObject object = YourObjectHere;
Map<String,Boolean> dict = new HashMap<String,Boolean>();
Iterator it = object.keyes();
while( it.hasNext() ){
String key = it.next();
String value = object.get(key);
dict.put( key, value );
}
Solution, more or less. //Written without checking in IDE so may contain bugs/errors
JSONObject json = new JSONObject(response);
json.getInt(keyA);
json.getString(keyB);
and etc;
You can using this function with httpResponse is your json string:
public static YourModel parseJson(String httpResponse) {
YourModel objObject = new YourModel();
try {
JSONArray jsonArrayData = new JSONArray(httpResponse);
if (jsonArrayData.length() >= 1) {
for (int i = 0; i < jsonArrayData.length(); i++) {
JSONObject object = new JSONObject(jsonArrayData.get(0));
// Setting value by key json
objObject.setAtrr(object.getString("YourKey"));
}
}
} catch (JSONException e) {
e.printStackTrace();
return null;
}
return objObject;
}

could not be able to get data from json webservice

I want to get data from a jason webservice,
JSON response is :
{"content":[{"id":"1","asset_id":"62","title":"sample page","alias":"","introtext":"","fulltext":"Some Contents"},{"id":"2","asset_id":"62","title":"sample page2","alias":"","introtext":"","fulltext":"Some Contents"},{"id":"3","asset_id":"62","title":"sample page3","alias":"","introtext":"","fulltext":"Some Contents"}]}
After Visiting Here
I have done in this way:
private void parseData() {
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(BASE_URL);
try {
// Getting Array of Contents
contents = json.getJSONArray(TAG_CONTENTS);
// looping through All Contents
for(int i = 0; i < contents.length(); i++){
JSONObject c = contents.getJSONObject(i);
// Storing each json item in variable
id = c.getString(TAG_ID);
title = c.getString(TAG_TITLE);
}
textView.setText(id + " " + title);
} catch (JSONException e) {
e.printStackTrace();
}
}
Now I got id = 3 and title = sample page3result now how can I get first two values as also!!?
Arshay!! Try This One Man!!
private void parseData() {
// Creating JSON Parser instance
MyJSONParser jParser = new MyJSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(BASE_URL);
try {
// Getting Array of Contents
jsonArrar = json.getJSONArray(TAG_CONTENTS);
List list = new ArrayList<String>();
// looping through All Contents
for(int i = 0; i < jsonArrar.length(); i++){
// JSONObject c = jsonArrar.getJSONObject(i);
String id1=jsonArrar.getJSONObject(i).getString(TAG_ID);
String title=jsonArrar.getJSONObject(i).getString(TAG_TITLE);
String fullText=jsonArrar.getJSONObject(i).getString(TAG_FULL_TEXT);
list.add(id1);
list.add(title);
list.add(fullText);
}
Iterator<String> iterator = list.iterator();
StringBuilder builder = new StringBuilder();
while (iterator.hasNext()) {
String string = iterator.next();
builder.append(string+"\n");
}
textView.setText(builder);
} catch (JSONException e) {
e.printStackTrace();
}
}
Your line is JSONObject and not JSONArray.
You should use it like that:
JSONObject jso = new JSONObject(line);
JSONArray jsa = new JSONArray(jso.getJSONArray("content"));
Try something like this
// jsonData : response
List< String> contents = new ArrayList< String>();
String[] val;
try {
JSONObject jsonObj = new JSONObject(jsonData);
if (jsonObj.get(JSON_ROOT_KEY) instanceof JSONArray) {
JSONArray array = jsonObj.optJSONArray(JSON_ROOT_KEY);
for (int loop = 0; loop < array.length(); loop++) {
val = new String[loop];
JSONObject Jsonval = array.getJSONObject(loop);
val.Jsonval.getString(TAG_ID);
val.Jsonval.getString(asset_id);
.
.
etc
contents.add(val);
}
}
}

Accessing json contents in android [duplicate]

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);
}

Categories

Resources