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.
Related
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");
}
I'm trying to convert a json object to a string using but I'm getting 'No Value for NAMES'. My code is as follows:
JSONObject jsonObject = new JSONObject(resp);
String c = jsonObject.getString("NAME");
msg("" + c);
Currently my object is as follows:
{"Names":[{"NAME":"Haircut"},{"NAME":"Blowdry"},{"NAME":"styling "},{"NAME":"treatment "},{"NAME":"braiding"}]}
How can I convert this data so that I may ingest the data into a listview dynamically.
Any help will be highly appreciated.
Names is and array in your JSON. So, firstly your should get it. Try this one:
JSONArray names = (JSONArray)jsonObject.get("Names");
((JSONObject) names.get(0)).get("NAME");
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...
}
}
Hi can any one help for this issue, i am not able to pass arraylist of values in bellow json array.
please help me.
Ex values:
Arraylist<String> list_values = new Arraylist<String>();
list_values.add(111);
list_values.add(222);
list_values.add(333);
Arraylist<String> list_labeltext = new Arraylist<String>();
list_labeltext.add("Mileage Entry");
list_labeltext.add("Tip Amount");
list_labeltext.add("Travel Time");
Arraylist<String> list_optionId = new Arraylist<String>();
list_optionId.add("1");
list_optionId.add("2");
list_optionId.add("3");
i want pass above array list values in json array like this:
ClockOUTEmployeeReponse":[{"Response":[{"Response":[{"Value":"111"}],"LabelText":"Mileage Entry","ClockOUTOptionId":2},{"Response":[{"Value":"222"}],"LabelText":"Tip Amount","ClockOUTOptionId":4},{"Response":[{"Value":"333"}],"LabelText":"Travel Time","ClockOUTOptionId":3}]
My Code is as follows:
JSONObject parentData = new JSONObject();
JSONArray req_parameters = new JSONArray();
JSONObject req_clockout_obj = new JSONObject();
JSONArray req_arr = new JSONArray();
JSONObject value = new JSONObject();
req_clockout_obj.put("ClockOUTOptionId", 1);
req_clockout_obj.put("LabelText", labelText);
for (int i = 0; i < list_values.size; i++) {
if (i == 0) {
value.put("Value", list_values.get(0));
req_arr.put(value);
req_clockout_obj.put("Response", req_arr);
} else if (i == 1) {
value.put("Value", list_values.get(1));
req_arr.put(value);
req_clockout_obj.put("Response", req_arr);
} else if (i == 2) {
value.put("Value", list_values.get(2));
req_arr.put(value);
req_clockout_obj.put("Response", req_arr);
}
}
req_parameters.put(req_clockout_obj);
parentData.put("ClockOUTEmployeeReponse", req_parameters);
Best way to implement this is using a Model Class and fetch data in a instance of that Model(POJO) then convert that into json string.
For this You need GSON library.
Steps :
1. Make a POJO(Model Class) of according to you json format.
2. Then fetch data in a object of that POJO.
3. Then U can convert that POJO's object into json using
DataObject obj = new DataObject();
Gson gson = new Gson();
// convert java object to JSON format,
// and returned as JSON formatted string
String json = gson.toJson(obj);
Please follow the following link :
http://www.mkyong.com/java/how-do-convert-java-object-to-from-json-format-gson-api/
Please use this, If you need any help then let me know.
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);
.....
}