How to parse this json and loop through each item and get its key string and value string.(keys are generated dynamically)
{
"business_industry_type": {
"11": "dummy1",
"2": "dummy2",
"44": "dummy3",
"4": "dummy4",
"5": "dummy5",
"34": "dummy6",
"7": "dummy7",
"88": "dummy8",
"9": "dummy9"
},
"status": "success",
"description": "Successfully ListedType",
"DES_CODE": "NC08"
}
Maybe this will help, try using Iterator to solve your problem.
Iterator<?> permisos = jsonObject.keys();
try {
while(permisos.hasNext() ){
String key = (String)permisos.next();
if(jsonObject.get(key) instanceof JSONObject) {
Iterator<?> tipo = jsonObject.getJSONObject(key).keys();
while (tipo.hasNext()) {
String key2 = (String) tipo.next();
Log.e("TAG", "Key: "+ key2 +" Value: "+jsonObject.getJSONObject(key).getString(key2).toString() );
}
}
else
Log.e("TAG", "Key: "+ key +" Value: "+jsonObject.getString(key) );
}
} catch (JSONException e) {
e.printStackTrace();
}
Related
I have the following json
[
{
"abc": "",
"type": "string"
},
{
"bcd": "",
"type": "dropdown"
},
{
"efg": "",
"type": "dropdown"
},
{
"hij": "",
"type": "string"
},
{
"klm": "",
"type": "string"
}
]
I am facing difficulties in parsing the json in Kotlin.
How can i parse this JSON from Retrofit API - Kotlin Suspend Function?
You can parse this json using mentioned function :
private void parseDynamicJson(JSONObject data) {
if (data != null) {
Iterator<String> keys = data.keys();
while (keys.hasNext()) {
String key = keys.next();
try {
if (data.get(key) instanceof JSONArray) {
JSONArray dataJSONArray = data.getJSONArray(key);
int size = dataJSONArray.length();
for (int i = 0; i < size; i++) {
parseDynamicJson(dataJSONArray.getJSONObject(i));
}
} else if (data.get(key) instanceof JSONObject) {
parseDynamicJson(data.getJSONObject(key));
} else {
System.out.println("parseDynamicJson" + key + ":" + data.getString(key));
}
} catch (Exception e) {
try {
System.out.println("parseDynamicJson" + key + ":" + data.getString(key));
} catch (Exception ee) {
ee.printStackTrace();
}
e.printStackTrace();
}
}
}
}
"2019-09-06 05:55:00": {
"1. open": "1221.6000",
"2. high": "1221.8000",
"3. low": "1219.7000",
"4. close": "1220.2000",
"5. volume": "149317"
},
"2019-09-06 05:50:00": {
"1. open": "1222.3500",
"2. high": "1223.4500",
"3. low": "1221.1500",
"4. close": "1221.5500",
"5. volume": "154134"
},
how to print on log of this json object name , (2019-09-06 05:55:00) in android.
for (int i = 0; i < jsonObject1.length(); i++) {
JSONObject json_data1 = jsonObject1.getJSONObject("2019-09-06 05:55:00");
Log.e(TAG, "parseResponse: json_data1"+json_data1 );
JsonObject objs2 = (JsonObject) jsonObject1.get("2019-09-06 05:55:00");
Log.e(TAG, "parseResponse: ............."+objs2);
}
Try this:
// Pass your json object in this method
public void parseJSONKeyValue(JSONObject jsonObject) {
try {
// Iterate your json object keys
Iterator iterator = jsonObject.keys();
// Initiate the for loop
while (iterator.hasNext()) {
// Parsing json keys
String jsonKey = (String) iterator.next();
// Parsing json values
String jsonValue = jsonObject.getString(jsonKey);
// Printing the log
Log.d("Json Data", "key: " + jsonKey + ", value: " + jsonValue);
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("OOPs!!", "Please check your json or something else bad happened!!");
}
}
Also, this JSON is not in the correct format, so you have to create a JSONArray for this.
I'm unable to fetch from this type of JSON, I'm confused in how to get data from inside of JsonObject, I got the value of "dealer_name", "phone_no" and "address" but I'm not getting the value of other.
This is my Solution.
JsonObjectRequest jsonObjReq = new JsonObjectRequest(
urlLink, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("suraj", response.toString());
try {
for (int i = 0; i < response.length(); i++) {
String name = response.getString("dealer_name");
String phone_no = response.getString("phone_no");
String add = response.getString("address");
JSONObject phone = (JSONObject) response.get(String.valueOf(i));
String acc_name = phone.getString("auto_dealer_id");
String acc_price = phone.getString("accessory_price");
jsonResponse = "";
jsonResponse += "dealer_name: " + name + "\n\n";
jsonResponse += "dealer_phone: " + phone_no + "\n\n";
jsonResponse += "dealer_add: " + add + "\n\n";
jsonResponse += "acc_name: " + acc_name + "\n\n";
jsonResponse += "acc_price: " + acc_price + "\n\n";
}
txt.setText(jsonResponse);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
Volley.newRequestQueue(Activity3.this).add(jsonObjReq);
}
This is my JSON data:-
{
"auto_dealer_id": "1",
"dealer_name": "RAJ MOTORS",
"phone_no": "9004296356",
"address": "THANE WEST 40002",
"0": {
"auto_dealer_accessory_id": "1",
"auto_dealer_id": "1",
"accessory_name": "CAR OILING",
"accessory_price": "40"
},
"1": {
"auto_dealer_accessory_id": "2",
"auto_dealer_id": "1",
"accessory_name": "CAR WASHING",
"accessory_price": "40"
},
"2": {
"auto_dealer_gallery_id": "1",
"auto_dealer_id": "1",
"image": "1.jog",
"status": "1",
"sort": "1",
"added_date": "0000-00-00 00:00:00"
}
}
try this code:
try
{
String jsonString="";//your json string here
JSONObject jObject= new JSONObject(jsonString);
Iterator<String> keys = jObject.keys();
while( keys.hasNext() )
{
String key = keys.next();
Log.v("key Items", key);
JSONObject innerJObject = jObject.getJSONObject(key);
Iterator<String> innerKeys = innerJObject.keys();
while( innerKeys.hasNext() )
{
String innerKkey = keys.next();
String value = innerJObject.getString(innerKkey);
Log.v("key = "+key, "value = "+value);
}
}
}
catch (JSONException e){
e.printStackTrace();
}
but it is better approach to convert you JsonObject "1","2"... to JsonArray
Since you want to get json object inside json object,
here you can get
JSONObject number = response.getJSONObject("1");
number.getString("auto_dealer_accessory_id")
and so on.
But there are some better approaches as well. Use Gson and also improve your data structure coming from server. using an array is better option and don't forget to check if the object or string exists before you try to get a value. you can use
jsonObject.has("key")
Try this:
ArrayList acc_name = new ArrayList();
...
...
try
{
JSONObject obj=new JSONObject(responseString);
String name = obj.getString("dealer_name");
String phone_no = obj.getString("phone_no");
String add = obj.getString("address");
Iterator<String> keys = obj.keys();
while( keys.hasNext() )
{
String key = keys.next();
JSONObject innerJObject = obj.getJSONObject(key);
Iterator<String> inKeys= innerJObject .keys();
while( inKeys.hasNext() )
{
String inKeys= keys.next();
acc_name.Add(innerJObject .getString(inKeys);
..
}
}
}
catch (JSONException e)
{ e.printStackTrace(); }
I have received a string value from JSON, but when I add that JSON value to a JSON array it gives an error stating that it can not convert String value to JSONArray. Please help me.
In the response there are a 3 values in "Value"
protected class AsyncMenuRate extends
AsyncTask<ForGettingRate, JSONObject, JSONObject> {
JSONObject jsonObj = null;
#Override
protected JSONObject doInBackground(ForGettingRate... params) {
RestAPI api = new RestAPI();
try {
jsonObj = api.MenuRate(params[0].getTableId(), params[0].getMenulist());
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("AsyncCreateUser", e.getMessage());
}
return jsonObj;
}
#TargetApi(Build.VERSION_CODES.KITKAT)
#Override
protected void onPostExecute(JSONObject objects) {
try {
//String ss= objects.getString("Value").;
JSONArray jarray=objects.getJSONArray("Value");
//jarray = new JSONArray(ss);
for (int i = 0; i < jarray.length(); i++) {
jsonObj = jarray.getJSONObject(i);
}
} catch (Exception e) {
e.printStackTrace();
}
Toast.makeText(DisplayActivity.this, "Successfully inserted...", Toast.LENGTH_LONG).show();
}
}
This is a function that I have return value:
String menuTotal = "0";
String item_rate;
public String MenuRate(int t_id, String menunameoflist) {
if (dbConnection.State.ToString() == "Closed") {
dbConnection.Open();
}
if (db.ChkDb_Value("select * from table_status where table_type='" + "A/C" + "'and t_id='" + t_id + "'"))
item_rate = db.getDb_Value("select rate from menu where m_name='" + menunameoflist + "' ").ToString(); // get the item rate from the tbl
else if (db.ChkDb_Value("select * from table_status where table_type='" + "Non A/C" + "'and t_id='" + t_id + "'"))
item_rate = db.getDb_Value("select non_ACrate from menu where m_name='" + menunameoflist + "' ").ToString(); // get the item rate from the tbl
else
item_rate = db.getDb_Value("select driverRate from menu where m_name='" + menunameoflist + "' ").ToString(); // get the item rate from the tbl
//menuRate = db.getDb_Value("select menu_id From menu where m_name='" + getMenuname + "'");
dbConnection.Close();
return item_rate;
}
This is the JSON format:
{
"name": "MenuRate",
"parameters": [
{
"name": "t_id",
"type": "int32"
},
{
"name": "menunameoflist",
"type": "string"
}
],
"returnvalue": "string"
}
This is function that I have get a response from JSON:
public JSONObject MenuRate(int t_id, String menunameoflist) throws Exception {
JSONObject result = null;
JSONObject o = new JSONObject();
JSONObject p = new JSONObject();
o.put("interface","RestAPI");
o.put("method", "MenuRate");
p.put("t_id",mapObject(t_id));
p.put("menunameoflist",mapObject(menunameoflist));
o.put("parameters", p);
String s = o.toString();
String r = load(s);
result = new JSONObject(r);
return result;
}
First your MenuRate method returns String not JSONObject. So you had to get that as String and convert it into JSONObject, as shown below.
#Override
protected JSONObject doInBackground(ForGettingRate... params) {
RestAPI api = new RestAPI();
try {
String jsonString = api.MenuRate(params[0].getTableId(), params[0].getMenulist());
return new JSonObject(jsonString);
} catch (Exception | JsonException e) {
// TODO Auto-generated catch block
Log.d("AsyncCreateUser", e.getMessage());
}
return jsonObj;
}
Don't forgot to add the JsonException, no problem some how it will ask to add the exception.
Now the string value is converted to JSON, so now you can fetch the values and while fetching use opt instead of get like optJsonArray("key") instead of getJsonArray("key") by this way we will get null value instead of exception, if the key is not present in the JSON.
Now coming to the "value" key access in your JSON response. Below is the JSON value which you have provided,
{
"name": "MenuRate",
"parameters": [{
"name": "t_id",
"type": "int32"
}, {
"name": "menunameoflist",
"type": "string"
}],
"returnvalue": "string"
}
In your question you have mentioned that you need access a json array with the key "Value". But in this there is no array with key "Value". So the below code will explain you how to access the "name" string value and "parameters" Json array.
try {
//Name String value...
String name = objects.optString("name");
//Parameter Json Array...
JSONArray parameterarray =objects.optJSONArray("parameters");
for (int i = 0; i < parameterarray.length(); i++) {
JsonObject jsonObj = parameterarray.optJSONObject(i);
}
} catch (Exception e) {
e.printStackTrace();
}
Hope this is helpful :)
Hi i am having a simple type of json response ,I have worked on JSON with keys but in this response i only have the values,Please see the response as below
json
{
status: "success",
country: [
{
1: "Afghanistan"
},
{
2: "Albania"
},
{
3: "Algeria"
},
{
4: "American Samoa"
},
{
5: "Andorra"
},
{
6: "Angola"
},
{
7: "Anguilla"
},
{
8: "Antarctica"
},
{
9: "Antigua and Barbuda"
},
{
10: "Argentina"
},
{.....
.
.
.
.
.so on..
So i want to parse this JSON and want to put both the values in an ArrayList of Hashmap,I have worked as below,But find no path to proceed,Hope some buddy will help me.
code
jsonObj = new JSONObject(jsonStr);
if (jsonObj.has("country")) {
CountryArray = jsonObj.getJSONArray("country");
if (CountryArray != null && CountryArray.length() != 0) {
// looping through All Contacts
System.out
.println("::::::::::::::::my talent size:::::::::::"
+ CountryArray.length());
Your Json is not correct please check below format for your requirement.
{
status: "success",
country: [
{
"name": "Afghanistan",
"value": 1
},
{
"name": "Albania",
"value": 2
},
{
"name": "Algeria",
"value": 3
},
{
"name": "American Samoa",
"value": 4
},
{
"name": "Andorra",
"value": 5
},
{
"name": "Angola",
"value": "6"
}
....
....
....
]
}
The "status","country" and all the "1","2", etc in the json array "country" are all keys and hence, must be in double quotes. In short, your JSON is invalid.
Example:
{
"status": "success",
"country": [
{
"1": "Afghanistan"
}
]}
I have done it my way and wasted time in changing JSON syntax as answers suggested,my code is as below.
code
String jsonStr = sh.makeServiceCall(allContriesURL,
BackendAPIService.GET);
try {
if (jsonStr != null) {
jsonObj = new JSONObject(jsonStr);
if (jsonObj.has("country")) {
CountryArray = jsonObj.getJSONArray("country");
if (CountryArray != null && CountryArray.length() != 0) {
// looping through All Contacts
System.out
.println("::::::::::::::::my talent size:::::::::::"
+ CountryArray.length());
for (int i = 0; i < CountryArray.length(); i++) {
JSONObject c = CountryArray.getJSONObject(i);
country_name = c.getString((i + 1) + "");
System.out
.println(":::::::::::::::::::COUNTRY NAME:::::::::::::::::::::"
+ country_name);
HashMap<String, String> countryMap = new HashMap<String, String>();
countryMap.put("country_id", i + 1 + "");
countryMap.put("name", country_name);
countryList.add(countryMap);
}
}
}
}
} catch (Exception e) {
System.out
.println("::::::::::::::::::::::;;EXCEPTION::::::::::::::::"
+ e);
}