JSON parsing assitance - android

I can log the JSON file in my app but I'm having troubles parsing the JSON file. I'm trying to get the name of each recipe so I can display it in a RecyclerView. I do need more data from the JSON later on, would it be better to do all the parsing at once or as needed?
Here is the link to the JSON
https://d17h27t6h515a5.cloudfront.net/topher/2017/May/59121517_baking/baking.json
JSONObject recipeObject = new JSONObject(jsonString);
JSONArray recipeResults = recipeObject.getJSONArray("name");
Log.d(LOGTAG, "Recipe Results " + recipeResults.toString());
This is the log result
2018-12-13 13:56:43.622 31472-31472/com.shawn.nichol.bakingapp W/System.err: at com.bakingapp.Data.ExtractRecipeData.recipeData(ExtractRecipeData.java:19)

The base object is an array of objects.
Try this:
JSONArray recipes = new JSONArray(jsonString);
for(int i = 0; i < recipes.length(); i++){
JSONObject recipe = recipes.getJSONObject(i);
Log.d(LOGTAG, "Recipe name: " + recipe.getString("name"));
}

first of all you need to use a tool to better understand your json structure I use jsoneditoronline see in the link the preview of your jsonobject
http://jsoneditoronline.org/?id=dac21affd6544a00a553360e2c9fa311
The parsing is better done at first then you pass your data to the RecyclerViewAdapter
this library should help you a lot https://github.com/google/gson
here is a tutorial for gson : https://howtodoinjava.com/apache-commons/google-gson-tutorial-convert-java-object-to-from-json/
Before trying to access name you need to access an item of the array let's say you need to get the name of the first object that is the nutella pie you do like this
JSONArray myJsonArray = new JSONArray(jsonString);
JSONObject recipeObject = myJsonArray.getJSONObject(0);
Log.d(LOGTAG, "Recipe Name" + recipeObject.getString("name").toString());
if you want to convert your JSON into java you need to
Recipe recipe= gson.fromJson(recipeObject.toString(), Recipe.class);
get all the data as so
List<Recipe> recipeList = new ArrayList();
Gson gson = new Gson();
for (int i = 0; i < jsonArray.length(); i++) {
Recipe recipe= gson.fromJson(myJsonArray .get(i).toString(), Recipe.class);
recipeList.add(recipe);
}

Related

How to get the multiple text from string in Android?

I am developing the Android for Xively. I get the following text data and store into string.
{"id":111111177,"title":"G-sensor","private":"true","feed":"https://api.xively.com/v2/feeds/111111177.json","auto_feed_url":"https://api.xively.com/v2/feeds/111111177.json","status":"frozen","updated":"2014-08-05T07:14:29.783670Z","created":"2014-08-01T08:29:17.156043Z","creator":"https://xively.com/users/x22819","version":"1.0.0","datastreams":[{"id":"GPIO1","current_value":"1","at":"2014-08-05T07:14:18.991421Z","max_value":"1.0","min_value":"0.0","tags":["xyz"],"unit":{"type":"G","label":"watts"}},{"id":"GPIO2","current_value":"0","at":"2014-08-05T07:14:29.783670Z","max_value":"1.0","min_value":"0.0","tags":["xyz"],"unit":{"type":"G","label":"watts"}},{"id":"GPIO3","current_value":"1","at":"2014-08-05T06:51:08.165217Z","max_value":"1.0","min_value":"1.0"},{"id":"GPIO4","current_value":"0","at":"2014-08-05T06:51:13.029452Z","max_value":"0.0","min_value":"0.0"},{"id":"GPIO5","current_value":"1","at":"2014-08-05T06:51:20.679123Z","max_value":"1.0","min_value":"1.0"},{"id":"GPIO6","current_value":"0","at":"2014-08-05T06:51:27.057369Z","max_value":"0.0","min_value":"0.0"}],"location":{"domain":"physical"},"product_id":"w8tuBsYf835kYTjDFz9w","device_serial":"DWJAXD6N7VDZ"}
There has id and the current_value in the above data , and I want to get the data of id and the current_value from the above text like following text.
GPIO1 1
GPIO2 0
GPIO3 1
GPIO4 0
GPIO5 1
GPIO6 0
How do I capture the the data of id and the current_value from the above text ?
Can somebody teach me how to do ?
Thank in advance.
Try this:
String resultJSON = "datastreams":[{"id":"GPIO1","current_value":"1","at":"2014-08-05T07:14:18.991421Z","max_value":"1.0","min_value":"0.0","tags":["xyz"],"unit":{"type":"G","label":"watts"}},
{"id":"GPIO2","current_value":"0","at":"2014-08-05T07:14:29.783670Z","max_value":"1.0","min_value":"0.0","tags":["xyz"],"unit":{"type":"G","label":"watts"}},
{"id":"GPIO3","current_value":"1","at":"2014-08-05T06:51:08.165217Z","max_value":"1.0","min_value":"1.0"},
{"id":"GPIO4","current_value":"0","at":"2014-08-05T06:51:13.029452Z","max_value":"0.0","min_value":"0.0"},
{"id":"GPIO5","current_value":"1","at":"2014-08-05T06:51:20.679123Z","max_value":"1.0","min_value":"1.0"},
{"id":"GPIO6","current_value":"0","at":"2014-08-05T06:51:27.057369Z","max_value":"0.0","min_value":"0.0"}],"location":{"domain":"physical"},"product_id":"w8tuBsYf835kYTjDFz9w","device_serial":"DWJAXD6N7VDZ"};
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 ID = jsonOBject.getString("id");
}
Hope this may help you
dataList = new ArrayList<HashMap<String, String>>();
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
myarray = jsonObj.getJSONArray("datastreams");
// looping through All myarray
for (int i = 0; i < myarray.length(); i++) {
JSONObject c = myarray.getJSONObject(i);
String id = c.getString("id");
String date = c.getString("at");
// tmp hashmap for single data
HashMap<String, String> data = new HashMap<String, String>();
// adding each child node to HashMap key => value
data.put(TAG_ID, id);
data.put(TAG_DATE, date);
// adding data to data list
dataList.add(data);
}
The data you have is actually a JSON so you can simply parse it to java POJO. I would suggest to use one of 2 most popular open source parsers GSON or Jackson.
What you have to do is:
Create java POJOs for chosen parser. To make it easier use this online tool http://www.jsonschema2pojo.org/
Copy generated java classes to your project.
Use JSON parser e.g. GSON
Let's say you named your main class as Example, with GSON you can parse it like this:
Gson gson = new Gson();
String data = ....//your JSON data
Example example = gson.fromJson(data, Example.class);
Data you would like to get will have own Java representation and will be available through getter method, e.g.:
List<Datastream> datastreams = example.getDatastreamList();
for (DataStream data : datastreams) {
String id = data.getId();
String currentValue = data.getCurrentValue();
}
Then you can do whatever you like. Please know that GSON can also read streams, so if you already parse stream to string you can skip it and pass that stream to Gson object directly.
If you don't want redundant POJOs or their parameters, you can remove them. GSON will handle it and simply ignore these values. Just make sure that data you are interested in keep the generated structure.
That's how I would do it.

how to access the json array in following format

i am trying to access the json data from server, I have accessed the first json array from file but I don't know how to access the another json array from that file. Any help would be appreciated.
my url of json file is as follows
String jsonurl" = "http:// 66.7.207.5 /homebites/list_business_category.php?b_id=18";"
I have accessed json array "business" as follows,
json_object_main = json_parser.getJSONObjectFromUrl(jsonurl
+ res_id);
Log.i("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", json_object_main + "");
if (json_object_main != null) {
try {
JSONArray json_array_header = json_object_main
.getJSONArray("business");
JSONArray j=json_object_main.getJSONArray("business_cat");
//JSONArray json_cat=json_parser.getJsonArayFromUrl(jsonurl+res_id);
now I want to access json array "business_cat"
how can I do that?
I think you are looking for this:
JSONArray j=json_object_main.getJSONArray("business_cat");
for(int i=0; i < j.length(); i++)
{
JSONObject jsonAttribs = j.getJSONObject(i);
//do whatever you want to do with the elements
jsonAttribs.getString("SOME_KEY");
}
Hope it helps!

How to parse JSON without title object in Android?

I've a json output which returns something like this :
[
{
"title":"facebook",
"description":"social networking website",
"url":"http://www.facebook.com"
},
{
"title":"WoW",
"description":"game",
"url":"http://us.battle.net/wow/"
},
{
"title":"google",
"description":"search engine",
"url":"http://www.google.com"
}
]
I am familiar with parsing json having the title object, but i've no clue about how to parse the above json as it is missing the title object. Can you please provide me with some hints/examples so i can check them and work on parsing the above code?
Note : I've checked a similar example here but it doesn't have a satisfactory solution.
Your JSON is an array of objects.
The whole idea around Gson (and other JSON serialization/deserialization) libraries is that you wind up with your own POJOs in the end.
Here's how to create a POJO that represents the object contained in the array and get a List of them from that JSON:
public class App
{
public static void main( String[] args )
{
String json = "[{\"title\":\"facebook\",\"description\":\"social networking website\"," +
"\"url\":\"http://www.facebook.com\"},{\"title\":\"WoW\",\"description\":\"game\"," +
"\"url\":\"http://us.battle.net/wow/\"},{\"title\":\"google\",\"description\":\"search engine\"," +
"\"url\":\"http://www.google.com\"}]";
// The next 3 lines are all that is required to parse your JSON
// into a List of your POJO
Gson gson = new Gson();
Type type = new TypeToken<List<WebsiteInfo>>(){}.getType();
List<WebsiteInfo> list = gson.fromJson(json, type);
// Show that you have the contents as expected.
for (WebsiteInfo i : list)
{
System.out.println(i.title + " : " + i.description);
}
}
}
// Simple POJO just for demonstration. Normally
// these would be private with getters/setters
class WebsiteInfo
{
String title;
String description;
String url;
}
Output:
facebook : social networking website
WoW : game
google : search engine
Edit to add: Because the JSON is an array of things, the use of the TypeToken is required to get to a List because generics are involved. You could actually do the following without it:
WebsiteInfo[] array = new Gson().fromJson(json, WebsiteInfo[].class);
You now have an array of your WebsiteInfo objects from one line of code. That being said, using a generic Collection or List as demonstrated is far more flexible and generally recommended.
You can read more about this in the Gson users guide
JSONArray jsonArr = new JSONArray(jsonResponse);
for(int i=0;i<jsonArr.length();i++){
JSONObject e = jsonArr.getJSONObject(i);
String title = e.getString("title");
}
use JSONObject.has(String name) to check an key name exist in current json or not for example
JSONArray jsonArray = new JSONArray("json String");
for(int i = 0 ; i < jsonArray.length() ; i++) {
JSONObject jsonobj = jsonArray.getJSONObject(i);
String title ="";
if(jsonobj.has("title")){ // check if title exist in JSONObject
String title = jsonobj.getString("title"); // get title
}
else{
title="default value here";
}
}
JSONArray array = new JSONArray(yourJson);
for(int i = 0 ; i < array.lengh(); i++) {
JSONObject product = (JSONObject) array.get(i);
.....
}

Android parsing JSON from REST web-service

I have a REST web service at http://susana.iovanalex.ro/esculap/ws2.php?key=abc&action=getpatientlist which returns a JSON payload similar to the one below:
[{"id":"15","nume":"Suciu","prenume":"Monica","location":"Cardiologie, Salon 4, Pat
2","alarm_pulse_min":"60","alarm_pulse_max":"90","alarm_oxy_min":"90"},
{"id":"101","nume":"Test Node","prenume":"Arduino","location":"UPT Electro,
B019","alarm_pulse_min":"50","alarm_pulse_max":"160","alarm_oxy_min":"93"},
{"id":"160","nume":"Vasilescu","prenume":"Ion","location":"Cardiologie, Salon 4, Pat
2","alarm_pulse_min":"60","alarm_pulse_max":"120","alarm_oxy_min":"80"},
{"id":"161","nume":"Lungescu","prenume":"Simion","location":"Pneumologie, Salon 5, Pat
5","alarm_pulse_min":"70","alarm_pulse_max":"110","alarm_oxy_min":"95"},
{"id":"162","nume":"Paunescu","prenume":"Ramona","location":"Cardiologie, Salon 4, Pat
2","alarm_pulse_min":"0","alarm_pulse_max":"0","alarm_oxy_min":"0"}]
When using Android's parser on following the tutorial from http://www.androidcompetencycenter.com/2009/10/json-parsing-in-android/ I want to return in an ArrayList the processed data.
I'm constantly getting the following error:
org.json.JSONException: Value [{"prenume":"Monica", ... "nume":"Paunescu"}] of type
org.json.JSONArray cannot be converted to JSONObject.
Could you please give me a code snippet or a pointer on where can I find some more info ?
Your whole Json is a JSONArray of JSONObjects.
Your trying to get a JSONObject i.e:
JSONObject jObject = new JSONObject("[{"prenume":"Monica", ... "nume":"Paunescu"}]");
but that is an Array!
Try:
JSONArray jArray = new JSONArray("[{"prenume":"Monica", ... "nume":"Paunescu"}]");
for(int i=0; i < jArray.length(); i++){
JSONObject jObject = jArray.getJSONObject(i);
String prenume = jObject.getString("prenume");
Log.i("TAG", "Prenume is: "+ prenume);
}
It's all explained here: http://www.json.org/ and here http://www.json.org/java/
see here http://www.json.org/ your web service contain an json Array not json Object so parse as:
JSONArray JSONArrays = new JSONArray(jString);
for(int n = 0; n < JSONArrays.length(); n++)
{
JSONObject object = JSONArrays.getJSONObject(n);
// do some stuff....
}
Best thing would be to use GSON for parsing the JSONAray string, that you received as output. this helps you to manage data as real objects, rather than Strings.
please have a look at the following post to parse your JSON array
How to Parse JSON Array in Android with Gson
only thing you need to do is create Classes with parameter names from your JSON output
You can refer this link
https://stackoverflow.com/a/11446076/1441666
{
"result": "success",
"countryCodeList":
[
{"countryCode":"00","countryName":"World Wide"},
{"countryCode":"kr","countryName":"Korea"}
]
}
Here below I am fetching country details
JSONObject json = new JSONObject(jsonstring);
JSONArray nameArray = json.names();
JSONArray valArray = json.toJSONArray(nameArray);
JSONArray valArray1 = valArray.getJSONArray(1);
valArray1.toString().replace("[", "");
valArray1.toString().replace("]", "");
int len = valArray1.length();
for (int i = 0; i < valArray1.length(); i++) {
Country country = new Country();
JSONObject arr = valArray1.getJSONObject(i);
country.setCountryCode(arr.getString("countryCode"));
country.setCountryName(arr.getString("countryName"));
arrCountries.add(country);
}
I think you should better use a library that can handle REST requests and objects serialization/deserialization for you out of box.
Take a look at Push Messages using REST api in android

how to parse JSON string with value as array

i need to parse the JSON data given below.
{"result":[{"bookId":142645,"bookpb":"MF",
"bookTs":1328999630000,"clipStatus":"D","bookDetail":{"arrival":1,"purchase":1,"sold":1},
"hierarchies":{"categories":["4"],"events":[]},"shopId":769752},
upto "sold" it is working fine.but when i am trying to parse categories it is not working.
given below is the code for parsing the data.
ArrayList<BookItem> resultdata = new ArrayList<BookItem>();
JSONArray jsonArray = (new JSONObject(inputString))
.getJSONArray("result");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
item = new BookItem();
item.setbookId(jsonObject.optString(book_ID));
item.setPurchase(jsonObject.optInt(PURCHASE));
item.setArrival(jsonObject.optInt(ARRIVAL));
item.setSold(jsonObject.optInt(SOLD));
item.setbookTs(jsonObject.optString(book_TS));
JSONObject hierarchies=jsonObject.getJSONObject(HIERARCHY);
item.setCategory(hierarchies.getInt("categories"));
resultdata.add(item);
}
can anybody help me???
i came to know that this is the problem of
{"categories":["4"],"events":[]}
data.how can i parse this array value?
categories is an JSONArray in order to get JSONArray
replace
item.setCategory(hierarchies.getInt("categories"));
with
item.setCategory(hierarchies.getJSONArray("categories").getInt(0));
For your purpose the best solution is probably GSON library. It do serialization and deserialization on its own and you will get your objects.
http://code.google.com/p/google-gson/

Categories

Resources