Android JSON multiple pairs parse - android

I have a JSONObject like this
{"message":{"context":"ws","data":"","id":"12345","http_accept":"json","method":"GET","search_key":"cat"},"response":{"1":"cat", "2":"catte"},"status":"OK","code":200}.
I am trying to get the result of a search webservice. I want the value of the pairs from the "response" key to add them to an ArrayList.
For example, from this "response" I want "cat" and "catte". How can I parse to get them?

Use a JSON Iterator to loop over all the keys and collect the response values.
JSONObject root = new JSONObject(jsonInput);
JSONObject resp = root.getJSONObject("response");
List<String> respList = new ArrayList<String>();
for (Iterator<String> iterator = resp.keys(); iterator.hasNext();) {
String key = iterator.next();
respList.add(resp.getString(key));
System.out.println(key + " = " + resp.getString(key));
}
System.out.println(respList);
Output :
1 = cat 2 = catte [cat, catte]

"response"s structure is map. You can easily parse it with Gson. example here

Related

JSON parsing assitance

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);
}

Android studio: How to receive Json Volley with different objects

According to this json file I want to receive data1 , xyz, abc object and their sub objects and show it in recyclerview.But I am receiving only data1 and their key-value pairs(index1 and name). I am using library Volley.
Can someone help me how to recive xyz and abc ?
{
"Data1":{
"index1":"4",
"name":"dan"
},
"xyz":{
"index1":"2",
"name":"jimi"
}
"abc":{
"index1":"5",
"name":"jordan"
}
}
JSONObject jsonObject = response.getJSONObject("Data1");
getset1.seti(jsonObject.getString("index1"));
getset1.setn(jsonObject.getString("name"));
Try this
JSONObject jsonobject=new JSONobject("");
for (int i=0;i<jsonobject.length();i++){
JSONObject jsonObject1=jsonobject.getJSONObject(i);
);
You have to use loop.As this is not an array so u have to fetch the all keys using iterator and then loop among them try this
Iterator<String> keys = json.keys();
while (keys.hasNext())
{
// Get the key
String key = keys.next();
// Get the value
JSONObject value = json.getJSONObject(key);
// parse inner string from value
}

How parse json object and json array together

i have two situation of Json output .
one is data that found and i have a json array and a json object like this:
{"data":"yes"}[{"id":"10","number":"7","text":"text7","desc":"text7_again","user_code":"0"},{"id":"11","number":"8","text":"text8","desc":"text8_again","user_code":"1"}]
other situation is that data not found :
{"data":"no"}
just one json object.
how parse this data in android client for support two situtaion?
First, you should validate your json in http://jsonlint.com/ if you test it you will look that is a wrong json. So, for make it right, in your server your response should look something like this:
{"data":"yes","response":[{"id":"10","number":"7","text":"text7","desc":"text7_again","user_code":"0"},{"id":"11","number":"8","text":"text8","desc":"text8_again","user_code":"1"}]}
And in that case, in android
JSONObject jsonObj = new JSONObject(response);
if (jsonObj.getString("data").compareTo("yes") == 0) {
JSONArray jsonArray = jsonObj.getJSONArray("response");
//To-Do another code
}
and that's all
Here is a possible case: (you need to fix your json format)
Success -
string resultJSON =
{"success":true,
"data":[
{"id":"10","number":"7","text":"text7","desc":"text7_again","user_code":"0"},
{"id":"11","number":"8","text":"text8","desc":"text8_again","user_code":"1"}]}
Failed -
string resultJSON =
{"success":false}
Then
JSONObject jsonRoot = new JSONObject(resultJSON);
bool isSuccess = jsonRoot.getBoolean("success");
if (isSuccess) {
// do the array parser
for(int i=0; i<jsonData.lenght;i++) {
JSONObject jsonObj = jsonData.getJSONObject(i);
String id = jsonObj.getString("id"); // get the value of id
String desc = jsonObj.getString("desc"); // and so on...
}
}

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.

Get JSONObject by ID from another JSONObject - Android

I have a little issue with parsing JSON String which I get from a web server. So my JSON looks something like this :
{
..........
"statistics":{
"660":{
"param_id":660,
"cat_id":2,
"param_title":"Number",
"param_value":"26",
"value_type":"singleline",
"elem_order":"1"}
,
"662":{
"param_id":662,
"cat_id":2,
"param_title":"Name",
"param_value":"Dani",
"value_type":"singleline",
"elem_order":"2"
}
// --||--
}
}
So I get a JSONObject statisics and I want to get JSONObjects from statistics, but the problem is that their name is different everytime.So I can't just do json.getJSONObject("660");. So any suggestions how can I do that?
You can do something like this :
if(jsonObj.has("statistics")){
Iterator<Object> keys = stats.keys();
while(keys.hasNext()){
String key = (String) keys.next();
JSONObject obj = new JSONObject();
obj = stats.getJSONObject(key);
// get JSON
}// end while
}//end if
use JSONObject.keys() to get key iterator, then getJsonObject( key) to get object.
Try below code-
JSONArray nameArray = statisics.names();
JSONArray valArray = statisics.toJSONArray(nameArray);
where names() method returns array of names and it is stored in nameArray and valArray contains array of values corresponding to valArray.
You can iterate using for loop over these array to get values.
use like this
JSONObject jsonOnb = json.getJSONObject("statistics") ;
JSONObject pagesObj = jsonOnb.getJSONObject(jsonOnb.names().getString(0));
Log.i("pageid", "pageid= " +pagesObj.get("param_id"));
Log.i("title", "title= " +pagesObj.get("cat_id"));
..............

Categories

Resources