Using GSon how to get multiple vaues from JSONObject - android

Hi the below is my response from format
object {6}
csdfgi_fgid : 4casdff9743a1-3f9asdf2-4
fesdfgedVsdfgersionsfdg : 7
sdfg : 28
feesdfgdStart : 0
fesdfedCsdfgoudfsgnt : 28
discover[28]
0{4}
DiscCat : Tip
templateCat{2}
name : tip.tp
version : 2
timestamp : 1421146871251
content{1}
I am getting these values using Serializable in class like below
#SerializedName("csdfgi_fgid")
public String sCdfsisdfId;
#SerializedName("feedVersion")
public Long lFesdfgedVsdfgfsersdfsion;
#SerializedName("feed")
public ArrayList<DiscoverModel> discover;
Now in the array list again there is a Json Object "templateCat" which has two parameters "name , version". Now how to get values from this JSON Object

First of all you need to assign all the JSONObject that you are getting in a POJO class. After that getting JSONObject(templateCat) from JSONArray(discover) you have to do looping. For example:
for(int i=0;i<discover.size();i++){
TemplateCat templateCat = discover.get(i).getTemplateCat();
String strName = templateCat.getName();
String strVersion = templateCat.getVersion();
//If you want to get all name and version as list. Add strName and strVersion to ArrayList. <br>
For Example : nameArray.add(strName);
versionArray.add(strVersion);
}

You'll have to get that JSON array first, iterate thru it and then use Gson to convert it into your desired object.
JSONObject rootJson = /* Get your JSON object here */;
JSONArray nestedArray = rootJson.getJsonArray("your_nested_json_array_name");
List<YourObject> objects;
for(int i = 0; i < nestedArray.size(); i++) {
String objectJsonString = nestedArray.get(i);
YourObject o = new Gson().fromJson(objectJsonString, YourObject.class);
objects.add(o);
}
..the last thing you'd need to do is to set our objects list to your desired instance.

Related

Convert object a JSON object to string

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

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.

JSON parsing into ListView Android

This is the JsonObject i get form parsing my url: {"status":0,"items":"1333333454510|-7611868|-7222457"
now i need to get the seperate numbers seperetly as long.
i also get an error if i try to convert it to string: org.json.JSONException: Value 1333333454510|-7611868|-7222457 at items of type java.lang.String cannot be converted to JSONObject
How? Thanks
here is some code
JSONObject obj = JSONParser.getJSONFromUrl(URL + "search", parameters);
String firstItem = obj.getJSONObject("items").toString();
Split your items using \\|.
Example :
String items= "1333333454510|-7611868|-7222457" ; //here you got items
String[] _items=items.split("\\|");
Now iterate loop and convert it into long using Long.ParseLong().
EDIT :
As Ashwin said you need to use json.getString("items"); to get items.
You can convert it into long using following code.
ArrayList<Long> longs=new ArrayList<Long>();
for(int i=0;i<_items.length;i++){
longs.add(Long.parseLong(_items[i]));
}
Use Split function to separate.
parse json to get items in items String
use jsonObject.getString instead of jsonObject.getJSONObject to avoid error.
String items= "1333333454510|-7611868|-7222457" ;
String[] itemsArray =items.split("\\|");
String response= "{"status":0,"items":"1333333454510|-7611868|-7222457"}" ; // ie, response contains the string.
JsonObject json= new JsonObject(response);
String item=json.getString("items");
String [] items =item.split("|");
Will get 3 numbers in the items array.
JsonObject json= new JsonObject(response);
String item=json.getString("items");
String [] items =item.split("|");
your problem is here
JSONObject obj = JSONParser.getJSONFromUrl(URL + "search", parameters);
String firstItem = obj.getJSONObject("items").toString();
so change it to
String firstItem = obj.getString("items").toString();
and then do split operations as suggested by others.
SO force always with you:)

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

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