Parsing Single JSON object in Android Studio - android

I have a JSON Object I want to parse at this URL https://api.adviceslip.com/advice with this content:
{"slip": { "id": 137, "advice": "You're not that important; it's what you do that counts."}}
I have written this code in Android Studio but it does not seem to work.
String jsonString = handler.httpServiceCall(url);
if (jsonString != null) {
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONObject slip = jsonObject.getJSONObject("slip");
String id = slip.getString("id");
Log.d("slip id:", id);
String advice = slip.getString("advice");
Log.d("slip adv:", advice);
HashMap<String, String> map = new HashMap<>();
map.put("id", id);
map.put("advice", advice);
adviceSlip.setText(map.get("advice"));
}
Any help would be appreciated :)

One problem is that you are trying to get a String on an Int object, and perhaps this is one of your errors, please change your
splip.getString("id");
by
slip.getInt("id);
Another one is that you are creating a HashMap<String,String> but the id you getting from the json is an Int and perhaps you should change it to use HashMap<Int,String>

You can get the value from the jsonobject and simple set that value on the textview.
String jsonString = handler.httpServiceCall(url);
if (jsonString != null) {
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONObject slip = jsonObject.getJSONObject("slip");
String id = slip.getString("id");
Log.d("slip id:", id);
String advice = slip.getString("advice");
adviceSlip.setText(advice);
}

Related

parse json response in android parse json object details with json array

This is my json response.
"hits" : [ {
"recipe" : {
"uri" : "http://www.edamam.com/ontologies/edamam.owl#recipe_ef498d1ca2ecb7104aa72d516af211d8",
"label" : "A Potato Dish for Julia Recipe",
"image" : "https://www.edamam.com/web-img/9bd/9bd993aeafaf4a439a59b5689ea6153f.jpg",
i need to get this as my list view response, i tried to add this by many ways but still i am getting blank screen as respose.
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray hits = jsonObj.getJSONArray("hits");
for (int i = 0; i < hits.length(); i++) {
JSONObject h = hits.getJSONObject(i);
JSONObject recipe = h.getJSONObject("recipe");
String Uri = recipe.getString("uri");
String Label = recipe.getString("label");
String Image = recipe.getString("image");
HashMap<String, String> recipe_ = new HashMap<>();
recipe_.put("uri", Uri);
recipe_.put("label", Label);
recipe_.put("image", Image);
recipeList.add(recipe_);
This is my solution what i was finding to call json object details by first calling json array then its object.

How to Fetch Records from JSON Having the Same Name into Android's java file

[{"UserID":"vishi"},{"UserID":"vish"}]
this is the json data that I am sending from php...
how can i get these values with same name in android
Thanks,
JSONArray array = new JSONArray(...);
int length = array.length() ;
for (int i = 0; i < length; i++) {
JSONObject obj = array.optJSONObject(i);
if (obj != null) {
String userId = obj.optString("UserID");
}
}
[
{
"UserID": "vishi" // key is UserId. value is vishi
},
{
"UserID": "vish"
}
]
The key UserID is the same. Just loop through the array and get the value
ArrayList<String> list = new ArrayList<String>();
JSONArray jr = new JSONArray("your json");
for(int i=0i<jr.length();i++)
{
JSONObject jb = jr.getJSONObject(i);
String value= jb.getString("UserID");
list.add(value);
}
Note:
Blackbelt's answer will also work and it also has null check cause optJSONObject() could return null also. This is a better way
Drawing from blackbelt's answer
JSONObject obj = array.optJSONObject(i);
if (obj != null) {
String userId = obj.optString("UserID");
}
From the docs
public JSONObject optJSONObject (String name)
Added in API level 1
Returns the value mapped by name if it exists and is a JSONObject. Returns null otherwise.

Get first object in the JSONObject using int variable

I need to get the string in extract object. but the JSON object contains some random variable, so when I call through JSONObject pg = qr.getJSONObject(0) I get an error stating I can't use an integer.
Here is the jsonobject:
{"query":
{"pages":
{"7529378":
{"pageid":7529378,
"ns":0,
"title":"Facebook",
"extract":"<p><b>Facebook</b> is an online social networking service.</p>"
}
}
}
}
I tried the following Key structure but failed.
Iterator<?> keys = pg.keys();
while( keys.hasNext() ){
String key = (String)keys.next();
if( pg.get(key) instanceof JSONObject ){
// get all values from JSONObject
str=pg.optString("extract");
//get ns, title, extract,.. in same way from jObjpages
}
}
Do something like:
JSONObject json = new JsonObject(your_main_string);
JSONObject query= json.getJsonObject("query");
JSONObject pages = query.getJsonObject("pages");
JSONObject id= pages .getJsonObject("7529378");
String extract = id.getString("extract");

How to get a value from JSON Object by a key?

How to get the value by key in a JSON object? I had used following code but it receives "org.json.JSONException". Advance thanks for any help.
String resultJSON = "{Data:[{\"AreaID\":\"13\", \"Phone\":\"654321\", \"RegionName\":\"Sivakasi\"}, {\"AreaID\":\"14\", \"Phone\":\"12345\", \"RegionName\":\"ANJAC\"}]}";
JSONObject jObject = new JSONObject(resultJSON);
JSONObject jsonObject = jObject.getJSONObject("Data");
Map<String,String> map = new HashMap<String,String>();
Iterator iter = jsonObject.keys();
while(iter.hasNext()){
String key = (String)iter.next();
String value = jsonObject.getString(key);
map.put(key,value);
Log.d("Key Value","key: "+key+" Value: "+value);
}
Logcat details
org.json.JSONException: Value [{"AreaID":"13","Phone":"654321","RegionName":"Sivakasi"},{"AreaID":"14","Phone":"12345","RegionName":"ANJAC"}] at Data of type org.json.JSONArray cannot be converted to JSONObject
The structure of your JSON is wrong, you should use a Key for the second JSONObject , like this:
{
Data: {
\"AreaID\": \"13\",
\"Phone\": \"654321\",
\"RegionName\": \"Sivakasi\"
},
\"KEY\": {
\"AreaID\": \"14\",
\"Phone\": \"12345\",
\"RegionName\": \"ANJAC\"
}
}
Or the DATA should be a JSONArray ( surrounded by [] ) like this :
{
Data: [
{
\"AreaID\": \"13\",
\"Phone\": \"654321\",
\"RegionName\": \"Sivakasi\"
},
{
\"AreaID\": \"14\",
\"Phone\": \"12345\",
\"RegionName\": \"ANJAC\"
}
]
}
NOTE : you can check if your json is valid or not here
Personnaly , i prefer the second way ( Using JSONArray) , because the data inside has the same attributes (AreaID, Phone, REgionName). To parse data in this case , your code should be someting like this :
String resultJSON = "{Data:[{\"AreaID\":\"13\", \"Phone\":\"654321\", \"RegionName\":\"Sivakasi\"}, {\"AreaID\":\"14\", \"Phone\":\"12345\", \"RegionName\":\"ANJAC\"}]}";
JSONObject jsonRoot = new JSONObject(resultJSON);
JSONArray jsonData = jsonRoot.getJSONArray("Data");
for(int i=0; i<jsonData.lenght;i++) {
JSONObject jsonOBject = jsonData.getJSONObject(i);
Log.d(TAG, "json ("+i+") = "+jsonOBject.toString());
// do what you want with your JSONObject , i.e :add it to an ArrayList of paresed result
String areaID = jsonOBject.getString("AreaID");
int phoneNumber = jsonOBject.getInt("Phone");
String regionName = jsonOBject.getString("RegionName");
}
This is invalid JSON format. Before you convert your string to JSON object format, be sure about it's valid or not.
Please check validity of your JSON.
Hope it may help.

data from a jsonobject in android

The below is called from a string url and returns a json object which has an json array inside, but something else is not working, can anyone show me how to access the data inside?
{"data":[{"8196":{"booking_id":"8150","client_id":"107","venue_id":null}}]
String jsonStr = "{\"data\":[{\"8196\":{\"booking_id\": \"8150\",\"client_id\": \"107\",\"venue_id\": null}}]}";
try {
JSONObject json = new JSONObject(jsonStr);
JSONArray array = json.getJSONArray("data");
for (int i = 0; i < array.length(); i++) {
JSONObject o = array.getJSONObject(i);
Iterator it = o.keys();
while (it.hasNext()) {
String name = (String) it.next();
o = o.getJSONObject(name);
int bookingId = o.getInt("booking_id");
int clientId = o.getInt("client_id");
int venueId = o.optInt("venue_id");
Log.v("TEST", String.format("Booking ID: %s -- Client ID: %s -- Venue ID: %s", bookingId, clientId, venueId));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
I guess this is what you'll want. By the way, the JSON you posted is malformed. It's missing a } in the end.
You first need to decode the JSON string. The JSON sting you got in return is actually a serialized version of a JSON object.
You need to decode that string into a native Java Object.
There are a number of methods to this in Java. You can start by checking out the Java section at json.org.
I think the problem is that the value of key venue_id is null. You can replace null value with empty string(""), try it.

Categories

Resources