How to retrieve JSONobject response specific value in Android - android

I want to store a particular value of JSONobject response in one variable.
My JSON response is a string:
{"username":"admin","password":"admin","mobile":"xxxxxxxxxx"}
And from this response I want to retrieve the mobile number.
Can Anyone help?

Your Json is
{"username":"admin","password":"admin","mobile":"xxxxxxxxxx"}
Parse it Easily
JSONObject jsonObject= new JSONObject(json_response);
String mobile= jsonObject.optString("mobile");

Use asynchttpclient library. Its easy to use and parse values.
add this line in app gradle,
compile 'com.loopj.android:android-async-http:1.4.9'
Then,
Let, String s = "{"username":"admin","password":"admin","mobile":"xxxxxxxxxx"}";
JSONObject jsonObject = new JSONObject(s);
String username = jsonObject.optString("username");
String mobile = jsonObject.optString("mobile");
String password = jsonObject.optString("password");

You need to do something like the below:
final JSONObject jsonObject = new JSONObject(response);
if (jsonObject.length() > 0) {
String mobile = jsonObject.optString("mobile");
Log.e("TAG", "mobile:"+mobile);
}

Related

How to convert JsonObject to String for store in session in servlet?

How to convert JsonObject to String for store in session in servlet?
JSONObject jSONObject = new JSONObject();
jSONObject.put("user", rs.getString("user").toString());
jSONObject.put("pass", rs.getString("pass").toString());
You can simply use
jSONObject.string();
but if this way doesn't satisfy your needs you can use the following way
to convert json object to json string you can use this library in your build gradle
compile 'com.google.code.gson:gson:2.7'
and in your code:
String string = new Gson().toJson(jSONObject );

What is the difference between JSONObject and JSONTokener?

I'm wondering what is the difference between using a JSONObject and JSONTokener to parse a JSON string.
I have seen examples where either of these classes were used to parse a JSON string.
For example, I parsed a JSON string like this:
JSONObject object = (JSONObject) new JSONTokener(jsonString).nextValue();
return object.getJSONObject("data").getJSONArray("translations").
getJSONObject(0).getString("translatedText");
But I also see examples where they simply use a JSONObject class (without using JSONTokener) to parse it:
String in;
JSONObject reader = new JSONObject(in);
JSONObject sys = reader.getJSONObject("sys");
country = sys.getString("country");
I read the description on this page, but still don't really get the difference. Is one better than the other performance wise and when should a JSONTokener be used?
Thanks!

How would I get a particular value from a JSON?

I'm trying to get a particular value from a field within a JSON file. This is my first time working with a JSON file so I'm not sure if I'm doing it correctly.
try {
URL url = new URL(API_URL + city +".json");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close();
return stringBuilder.toString();
}
This block would get the JSON from a weather website and then return the JSON as a string. This string would then be used below. Unfortunately whenever I run this app in Android Studio and go through the logs the logs constantly say that there was no value in weather.
protected void onPostExecute(String response) {
if(response == null) {
response = "THERE WAS AN ERROR";
}
progressBar.setVisibility(View.GONE);
Log.i("INFO", response);
responseView.setText(response);
// TODO: check this.exception
// TODO: do something with the feed
try {
JSONObject object = (JSONObject) new JSONTokener(response).nextValue();
String weather = object.getString("weather");
Toast.makeText(MyActivity.this, "There is rain", Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
What I'm trying to do is grab information from the weather section
Here is the JSON link I'm trying to parse from. This text box thought there were too many links in the JSON response for me to post it here. I'm trying to figure out what is going on and any help would be greatly appreciated.
You can print out response to see if it is exactly your JSON or not.
Assume you get the JSON String correctly.
JSONObject object = new JSONObject(response);
String weather = object.getString("weather");
However, if the JSON your obtained is exactly your response, the above code do not work because there is not weather String. The root only contain response and current_observation.
If what you what to get is weather under current_observation, you should use the code below.
JSONObject object = new JSONObject(response);
JSONObject current_obs = object.getJSONObject("current_observation");
String weather = current_obs.getString("weather"); // Clear
JSONObject object = (JSONObject) new JsonObject(responseString);
String weather = object.getString("weather");
First you need to get your response in string.
Now,start json parsing as per response.
OR
You can use Gson class as well for json parsing.
Get json value from JSONObject:
{"weather":"sunny"}
code snippet to parse the JSONObject.
JSONObject object = new JsonObject(response);
String weather= object.getString("weather");
Get json value from JSONArray:
[{"name":"name1","url":"url1"},{"name":"name2","url":"url2"},...]
code snippet to parse the JsonArray.
JSONArray jsonarray = new JSONArray(response);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String name = jsonobject.getString("name");
String url = jsonobject.getString("url");
}
Hope it'll help you.
I have a sample Weather app done using open weather map api. It has all you asked for.
Code here:
http://opensourceandroid.in/weather_forecast.html

how to get code from json object

I am working with volley for network calling in android. my webservice is send me response object like that
{
   "Code": 200,
   "Message": "Record Found",
   "Result": {
      "deviceid": 10,
      "udid": "359447060356151",
      "businessid": 1,
      "usertype": "Merchant"
   }
}
now i want to read the code and message from this object. but failed to do so. I am using this code for getting this data.
JSONObject jsonObj = new JSONObject(response);
JSONObject userDetails = jsonObj.getJSONObject("Result");
LoginResponse entryObj = new LoginResponse();
entryObj.businessid = userDetails.getInt("businessid");
lr.businessid = entryObj.businessid;
Utilities.businessId = lr.businessid;
help me to read the code from this object. i am not getting the exact solution.
int code = jsonObj.getInt("Code");
String message = jsonObj.getString("Message");
This is how you read code and message.
Hey you can get code string from json using parsing,
JsonObject jsonObj=new jsonObject(response);
String code=jsonObj.optString("Code");
Do like this:
int code = jsonObj.getInt("Code");
String message = jsonObj.getString("Message");

How to parse a JSON string in android

My web service outputs a JSON string that I need to parse.
Could you please tell me how i can parse the given JSON string:
{
"access_token":"kfwsfdcscfnsdcfsdsdfsd6f7df9sd6f89sd6s",
"expires_in":3600,
"token_type":"bearer",
"scope":null,
"refresh_token":"5dfddf1d6dfd1fddgdgdg1dg56d1"
}
JSONObject mainObject = new JSONObject(Your_Sring_data);
JSONObject uniObject = mainObject.getJSONObject("university");
String uniName = uniObject.getJSONObject("name");
String uniURL = uniObject.getJSONObject("url");
JSONObject oneObject = mainObject.getJSONObject("1");
String id = oneObject.getJSONObject("id");
refer this link:
http://stackoverflow.com/questions/8091051/how-to-parse-json-string-in-android
String jsonString = ""; //This'll contain the jsonString you mentioned above.
JSONObject object = new JSONObject(jsonString);
String accessToken = object.getString("access_token");
Similarly fetch other values.
{ // represents json object node
"access_token":"kfwsfdcscfnsdcfsdsdfsd6f7df9sd6f89sd6s", // key value pair
To parse
JSONObject jb = new JSONObject("jsonstring");
String acess_token = jb.getString("acess_token"); // acess_token is the key
// similarly others
You can also use Gson to convert json string to java object.
http://code.google.com/p/google-gson/
Using Gson
Download the jar add to the projects libs folder
Then
public class Response {
String acess_token,expires_in,token_typerefresh_token;
}
Then
InputStreamReader isr = new InputStreamReader (is);
Gson gson = new Gson();
Response lis = new Gson().fromJson(isr, Response.class);
Log.i("Acess Toekn is ",""+lis.expires_in);
JSONObject jsonObject = new JSONObject(jsonString);

Categories

Resources