How to use Json Parsing? - android

Following is My Json File:-
"Restaurants":{
"8":{
"Res_name":"Purple Cafe and Wine Bar",
"foodtype":"American, Wine",
"city":"Seattle",
"state":"WA",
"latitude":"0",
"longitude":"0"
},
"9":{
"Res_name":"Quinn's",
"foodtype":"American, Pubs",
"city":"Seattle",
"state":"WA",
"latitude":"0",
"longitude":"0"
},
"19":{
"Res_name":"Dahlia Lounge",
"foodtype":"American",
"city":"Seattle",
"state":"WA",
"latitude":"0",
"longitude":"0"
},
},
I am Using below code for json parsing:-
try {
JSONObject jsonObj = new JSONObject(res);
JSONObject mRestaurant = jsonObj.getJSONObject("Restaurants");
String mResult = jsonObj.getString("Result");
System.out.println("mRestaurant is:- " + mRestaurant);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The mRestaurant Value is below:-
{"487":{"state":"WA","Res_name":"SAM Taste","longitude":"0","latitude":"0","foodtype":"American","city":"Seattle"},"332":{"state":"WA","Res_name":"Luna Park Cafe","longitude":"0","latitude":"0","foodtype":"American","city":"Seattle"},"35":{"state":"WA","Res_name":"Restaurant Zoe","longitude":"0","latitude":"0","foodtype":"American, Bar","city":"Seattle"},"
but what is the next step for getting Res_Name, foodtype from above response.
Any Help would be appreciated.

The below code is next step for json parsing.
public void getdata() {
String res = mWebRequest.performGet(Constants.url+ "restaurants.php? action=searchRestaurant&lat=0&lon=0&foodtype="+ mEdttxtSearch.getText().toString() + "&state="+ mEdttxtSearch.getText().toString() + "&city="+ mEdttxtSearch.getText().toString()+ "&devType=Android");
System.out.println("res is:- " + res);
if (res != null) {
try {
JSONObject jsonObj = new JSONObject(res);
JSONObject mRestaurants = jsonObj.getJSONObject("Restaurants");
String mResult = jsonObj.getString("Result");
if (jsonObj.has("Restaurants")) {
Iterator<Object> keys = mRestaurants.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
JSONObject obj = new JSONObject();
obj = mRestaurants.getJSONObject(key);
mRes_Name.add(obj.getString("Res_name"));
mLatitude.add(obj.getString("latitude"));
mLongitude.add(obj.getString("longitude"));
mState.add(obj.getString("state"));
mCity.add(obj.getString("city"));
mFood_Type.add(obj.getString("foodtype"));
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Use the get() method:
String mRestaurant = jsonObj.get("487").get("Res_name");

use gson for the same, as it supports direct conversion from json to java and java to json, please see following link:
Converting JSON to Java

Related

How to get Multiple return value From JSON in Android

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 :)

conversion from string to JSON object Android

I am working on an Android application. In my app I have to convert a string to JSON Object, then parse the values. I checked for a solution in Stackoverflow and found similar issue here link
The solution is like this
`{"phonetype":"N95","cat":"WP"}`
JSONObject jsonObj = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}");
I use the same way in my code . My string is
{"ApiInfo":{"description":"userDetails","status":"success"},"userDetails":{"Name":"somename","userName":"value"},"pendingPushDetails":[]}
string mystring= mystring.replace("\"", "\\\"");
And after replace I got the result as this
{\"ApiInfo\":{\"description\":\"userDetails\",\"status\":\"success\"},\"userDetails\":{\"Name\":\"Sarath Babu\",\"userName\":\"sarath.babu.sarath babu\",\"Token\":\"ZIhvXsZlKCNL6Xj9OPIOOz3FlGta9g\",\"userId\":\"118\"},\"pendingPushDetails\":[]}
when I execute JSONObject jsonObj = new JSONObject(mybizData);
I am getting the below JSON exception
org.json.JSONException: Expected literal value at character 1 of
Please help me to solve my issue.
Remove the slashes:
String json = {"phonetype":"N95","cat":"WP"};
try {
JSONObject obj = new JSONObject(json);
Log.d("My App", obj.toString());
} catch (Throwable t) {
Log.e("My App", "Could not parse malformed JSON: \"" + json + "\"");
}
This method works
String json = "{\"phonetype\":\"N95\",\"cat\":\"WP\"}";
try {
JSONObject obj = new JSONObject(json);
Log.d("My App", obj.toString());
Log.d("phonetype value ", obj.getString("phonetype"));
} catch (Throwable tx) {
Log.e("My App", "Could not parse malformed JSON: \"" + json + "\"");
}
try this:
String json = "{'phonetype':'N95','cat':'WP'}";
You just need the lines of code as below:
try {
String myjsonString = "{\"phonetype\":\"N95\",\"cat\":\"WP\"}";
JSONObject jsonObject = new JSONObject(myjsonString );
//displaying the JSONObject as a String
Log.d("JSONObject = ", jsonObject.toString());
//getting specific key values
Log.d("phonetype = ", jsonObject.getString("phonetype"));
Log.d("cat = ", jsonObject.getString("cat");
}catch (Exception ex) {
StringWriter stringWriter = new StringWriter();
ex.printStackTrace(new PrintWriter(stringWriter));
Log.e("exception ::: ", stringwriter.toString());
}
just try this ,
finally this works for me :
//delete backslashes ( \ ) :
data = data.replaceAll("[\\\\]{1}[\"]{1}","\"");
//delete first and last double quotation ( " ) :
data = data.substring(data.indexOf("{"),data.lastIndexOf("}")+1);
JSONObject json = new JSONObject(data);
To get a JSONObject or JSONArray from a String I've created this class:
public static class JSON {
public Object obj = null;
public boolean isJsonArray = false;
JSON(Object obj, boolean isJsonArray){
this.obj = obj;
this.isJsonArray = isJsonArray;
}
}
Here to get the JSON:
public static JSON fromStringToJSON(String jsonString){
boolean isJsonArray = false;
Object obj = null;
try {
JSONArray jsonArray = new JSONArray(jsonString);
Log.d("JSON", jsonArray.toString());
obj = jsonArray;
isJsonArray = true;
}
catch (Throwable t) {
Log.e("JSON", "Malformed JSON: \"" + jsonString + "\"");
}
if (object == null) {
try {
JSONObject jsonObject = new JSONObject(jsonString);
Log.d("JSON", jsonObject.toString());
obj = jsonObject;
isJsonArray = false;
} catch (Throwable t) {
Log.e("JSON", "Malformed JSON: \"" + jsonString + "\"");
}
}
return new JSON(obj, isJsonArray);
}
Example:
JSON json = fromStringToJSON("{\"message\":\"ciao\"}");
if (json.obj != null) {
// If the String is a JSON array
if (json.isJsonArray) {
JSONArray jsonArray = (JSONArray) json.obj;
}
// If it's a JSON object
else {
JSONObject jsonObject = (JSONObject) json.obj;
}
}
Using Kotlin
val data = "{\"ApiInfo\":{\"description\":\"userDetails\",\"status\":\"success\"},\"userDetails\":{\"Name\":\"somename\",\"userName\":\"value\"},\"pendingPushDetails\":[]}\n"
try {
val jsonObject = JSONObject(data)
val infoObj = jsonObject.getJSONObject("ApiInfo")
} catch (e: Exception) {
}
Here is the code, and you can decide which
(synchronized)StringBuffer or
faster StringBuilder to use.
Benchmark shows StringBuilder is Faster.
public class Main {
int times = 777;
long t;
{
StringBuffer sb = new StringBuffer();
t = System.currentTimeMillis();
for (int i = times; i --> 0 ;) {
sb.append("");
getJSONFromStringBuffer(String stringJSON);
}
System.out.println(System.currentTimeMillis() - t);
}
{
StringBuilder sb = new StringBuilder();
t = System.currentTimeMillis();
for (int i = times; i --> 0 ;) {
getJSONFromStringBUilder(String stringJSON);
sb.append("");
}
System.out.println(System.currentTimeMillis() - t);
}
private String getJSONFromStringBUilder(String stringJSONArray) throws JSONException {
return new StringBuffer(
new JSONArray(stringJSONArray).getJSONObject(0).getString("phonetype"))
.append(" ")
.append(
new JSONArray(employeeID).getJSONObject(0).getString("cat"))
.toString();
}
private String getJSONFromStringBuffer(String stringJSONArray) throws JSONException {
return new StringBuffer(
new JSONArray(stringJSONArray).getJSONObject(0).getString("phonetype"))
.append(" ")
.append(
new JSONArray(employeeID).getJSONObject(0).getString("cat"))
.toString();
}
}
May be below is better.
JSONObject jsonObject=null;
try {
jsonObject=new JSONObject();
jsonObject.put("phonetype","N95");
jsonObject.put("cat","wp");
String jsonStr=jsonObject.toString();
} catch (JSONException e) {
e.printStackTrace();
}

Android JSON object Parsing, unable to get status

{"Sam":{"status":"available","classkey":"dotnet"}}
How to parse this type of json?
try {
JSONObject jObj = new JSONObject(json);
if(jObj != null){
domtdl = jObj.getString(dom);
try {
JSONObject c = new JSONObject(domtdl);
if(c != null){
status = c.getString(TAG_STATUS);
System.out.println(status);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
Is it correct?
I do not know how to get data from second JSON object.
Please help me.
For this specific json string {"Sam":{"status":"available","classkey":"dotnet"}}
you need to do
try {
JSONObject jObj = (new JSONObject(json)).getJSONObject("Sam");
String status = jObj.getString("status");
String classkey = jObj.getString("classkey");
} catch (JSONException e) {
e.printStackTrace();
}
try
{
JSONObject jb = new JSONObject(myjsonstring);
JSONObject job = jb.getJSONOBject("Sam");
String status = job.getString("status");
Log.i("Status is",status);
String classkey = job.getString("classkey");
Log.i("Class Key is",classkey);
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
{ represents a json object node
{ // json object node
"Sam": { // json object SAM
"status": "available", json string
"classkey": "dotnet" json string
}
}
JSON Tutorial #
http://www.w3schools.com/json/
Your json can also look like below sometimes.
[ represents json array node
{
"employees": [
{
"firstName": "John",
"lastName": "Doe"
},
{
"firstName": "Anna",
"lastName": "Smith"
},
{
"firstName": "Peter",
"lastName": "Jones"
}
]
}
To parse the above
StringBuilder sb = new StringBuilder();
try {
JSONObject jb = new JSONObject(myjsonstring);
JSONArray jarr = jb.getJSONArray("employees");
for(int i=0;i<jarr.length();i++)
{
JSONObject job = jarr.getJSONObject(i);
String firstname = job.getString("firstName");
String lastname = job.getString("lastName");
sb.append(firstname);
Log.i("firstname",firstname);
sb.append("\n");
Log.i("lastname",lastname);
}
Toast.makeText(getApplicationContext(), sb, 10000).show();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

How to parse the Json response in android?

i m getting this response in a result of GET request to server
{"LL": { "control": "dev/sys/getkey", "value": "4545453030304138303046392035343733373432363020323031332D30322D31312031383A30313A3135", "Code": "200"}}
i just want to extract the value of "value" from the above json response.
I m using this code to get this response
findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
HttpResponse response = null;
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(
"http://192.168.14.247/jdev/sys/getkey"));
response = client.execute(request);
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String responseText = null;
try {
responseText = EntityUtils.toString(response.getEntity());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.i("Parse Exception", e + "");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.i("IO Exception 2", e + "");
}
Log.i("responseText", responseText);
Toast.makeText(MainActivity.this, responseText + "",
Toast.LENGTH_SHORT).show();
}
});
my question is that how can i parse this and get the value of only "value" tag.
thanks
you can parse current json String to get value from it as :
// Convert String to json object
JSONObject json = new JSONObject(responseText);
// get LL json object
JSONObject json_LL = json.getJSONObject("LL");
// get value from LL Json Object
String str_value=json_LL.getString("value"); //<< get value here
try this
JSONObject json = (JSONObject) JSONSerializer.toJSON(responseText);
String value = json.getJSONObject("LL").getString("value");
Try this:
JSONObject json= json1.getJSONObject("LL");
String value= json.getString("value");
Try this,
JSONObject ResponseObject = new JSONObject(Response);
String str = ResponseObject.getJSONObject("LL").getString(value);
You can parse your response and get value try this:
try {
JSONObject jsonObject = new JSONObject(response);// Convert response string in to json object.
JSONObject jsonLL = jsonObject.getJSONObject("LL");// Get LL json object from jsonObject.
String strValue = jsonLL.getString("value");// Get value from jsonLL Object.
} catch (Exception e) {
e.printStackTrace();
}
Simple and Efficient solution : Use Googlle's Gson library
Put this in build.gradle file : implementation 'com.google.code.gson:gson:2.6.2'
Now convert the JSON String to a convenient datastrucutre like HashMap in 2 lines like this.
Type type = new TypeToken<Map<String, String>>(){}.getType();
Map<String, String> myMap = gson.fromJson(JsonString , type);
or you can use this below class :
To convert your JSON string to hashmap use this :
HashMap<String, Object> hashMap = new HashMap<>(Utility.jsonToMap(response)) ;
Use this class :) (handles even lists , nested lists and json)
public class Utility {
public static Map<String, Object> jsonToMap(Object json) throws JSONException {
if(json instanceof JSONObject)
return _jsonToMap_((JSONObject)json) ;
else if (json instanceof String)
{
JSONObject jsonObject = new JSONObject((String)json) ;
return _jsonToMap_(jsonObject) ;
}
return null ;
}
private static Map<String, Object> _jsonToMap_(JSONObject json) throws JSONException {
Map<String, Object> retMap = new HashMap<String, Object>();
if(json != JSONObject.NULL) {
retMap = toMap(json);
}
return retMap;
}
private static Map<String, Object> toMap(JSONObject object) throws JSONException {
Map<String, Object> map = new HashMap<String, Object>();
Iterator<String> keysItr = object.keys();
while(keysItr.hasNext()) {
String key = keysItr.next();
Object value = object.get(key);
if(value instanceof JSONArray) {
value = toList((JSONArray) value);
}
else if(value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
map.put(key, value);
}
return map;
}
public static List<Object> toList(JSONArray array) throws JSONException {
List<Object> list = new ArrayList<Object>();
for(int i = 0; i < array.length(); i++) {
Object value = array.get(i);
if(value instanceof JSONArray) {
value = toList((JSONArray) value);
}
else if(value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
list.add(value);
}
return list;
}
}
Thank me later :)

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