Android, Iterate over JSON-fied dictionary - android

I have the following string, which was created using javascript JSON. (It's passed from a Webview to the native code using JavascriptInterface.)
{"var1":1,"var2":8}
How do I convert that into an object and then iterate over the key/value pairs? The names of the keys are NOT known in advance.
I have seen this JSON Array iteration in Android/Java and this Converting json string to java object? and this how to convert JSON string to object in JAVA android.
None of those seem to fit with my example, which is a dictionary with unknown key names. At least, it's certainly not clear to me which of the 15+ answers is relevant for my case.

The org.json library comes "for free" with Android, so I'd go with that. Usage when you don't know the keys ahead of time could be something like this:
try {
JSONObject jsonObject = new JSONObject(/* your json String here */);
Iterator<String> keys = jsonObject.keys();
while (keys.hasNext()) {
String key = keys.next();
String value = jsonObject.getString(key);
// do whatever you want with key/value
}
}
catch (JSONException e) {
// thrown when:
// - the json string is malformed (can't be parsed)
// - there's no value for a requested key
// - the value for the requested key can't be coerced to String
}

You can use it by converting the getting the json length like this:-
JSONObject obj = new JSONObject(response);
for (int i = 0; i < obj.length(); i++) {
//getting the json object of the particular index inside the array
JSONObject heroObject = obj.getJSONObject(i);
String aka=heroObject.getString("your key here");
}

Related

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 to use single word as JSON data in android?

I am trying to extract the JSON data which is just a single word. I have used JSON Array when it was a long list of a set of data but this time it just a word like - done or failed.
My Code is -
JSONObject jsonObject = new JSONObject(s);
//JSONArray jsonArray = jsonObject.getJSONArray("contacted");
loggingTest = jsonObject.getString("??"); // what to put here (??) as
//there is just a single word.
It may be very easy to get it but I feels I am missing something. Thanks for your help in advance.
URL just gives a word like - done that's it not even " or : { nothing
Then simply use the String variable s , don't convert it into json
plus you can put this JSONObject jsonObject = new JSONObject(s); in try-catch to recognize that respose is simply a valid json or not , if not it will throw an exception
try{
// exception will be thrown in case of invalid json
JSONObject jsonObject = new JSONObject(s);
}
catch(JSONException e){
// s containing a single word so use it as it is
}

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