JSON Parsing - JSONObject without JSONArray - android

I have a api like this
-{
- meta {
item1: value;
item2: value;
item3: value;
},
- object [
{
- category {
id: 1;
...
}
- File {
...
}
},
{
- category {
id:2;
...
}
- File {
...
}
}
]
I dont have any problem to parse JSONArray of "obejct" and it's JSONObjects...
I do like this:
private static final String TAG_NOD = "object";
private static final String TAG_CAT = "category";
private static final String TAG_CAT_ID = "id";
private static final String TAG_CAT = "File";
JSONArray Items = null;
JSONObject jsonObj = new JSONObject(jsonstr); // jsonstr is loaded url by httpcal
Items = jsonObj.getJSONArray(TAG_NOD);
for ( int i=0; i<Items.length(); i++){
JSONObject childs = Items.getJSONObject(i);
JSONObject category= child.getJSONOBject(TAG_CAT);
// getting category items in string like String ID = category.getString(TAG_CAT_ID);
JSONObject file = Item.getJSONObject(TAG_FILE)
// getting file items in string like file.getString(String name)
HashMap<String, String> items = new HashMap<String, String>();
items.put(TAG_CAT_ID, ID);
.
.
.
ItemLis.add(items); //Itemlist is a ArrayList<HashMap<String, String>>()
}
but my problem is to parsing jsonobject of "meta" and add its data to my ListItem Arraylist
any solution appreciated :D

Like this:
JSONObject meta = jsonObj.getJSONObject("meta");
Iterator<String> iterator = meta.keys();
HashMap<String,String> metaMap = new HashMap<String,String>();
while (it.hasNext()) {
String key = iterator.next();
String value = meta.getString(key);
metaMap.put(key,value);
}
ItemLis.add(items);
Also, if I may, here are a couple of quick suggestions on some things I've noticed that could improve your coding style:
Per Java naming conventions, variables and member names start with a lower case letter, so it should be itemLis instead of ItemLis. You already do this on most of your names except for ItemLis and Items. While this is not a must, following convention will make your code more readable, not only to you, but also when you seek help here on SO.
Unless you specifically require that the items in ItemLis be HashMaps (that is, your algorithm will not work with any other Map implementation), it's usually considered good practice to hide that detail from the implementation. I.e. instead of HashMap<...> items = new HashMap, go like Map<...> items = new HashMap, and change the type of ItemLis from <ArrayList<HashMap<...>> to List<Map<...>>. That way, if you ever decide to change the implementation backing the list or map, your code changes will be confined to only one place, instead of breaking much of your code. As a rule of thumb: Try to declare types with the most abstract type you require.

You can use the GSON lib. Very simple and fast implemented. Best practise at this case.
Just create an object which looks like your json string.
Then call:
Gson gson = new Gson();
YourObject obj = gson.fromJson(jsonString, YourObject.class);
Then you have the data in an object and can use it with getter and setter. Maybe you have to annotate the variables in the object. For that take a look here: https://code.google.com/p/google-gson/

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.

Parsing JsonObject's fields regardless of their name

I've been looking for this for a while now, but couldn't find it anywhere in SO or in the docs.
I am using Gson to parse a json file, and suppose the file is:
{
"animal":"cat",
"paws":"4",
"eyes":"2"
}
Now, since all the fields are strings, I want to parse it as an array of strings, I want something like:
{"cat","4","2"}
And I would like to parse the JsonObject regardless of the name of its tags, and that's where the problem lies. I can garantee the json will contain only strings, but I have no clue of what the fields are going to be named.
Anyone ever faced this problem ? Any help is much appreciated, and any research direction also.
Edit
From the anwers, I managed to do it like this:
for (Map.Entry<String, JsonElement> entry : object.entrySet()) {
// do your stuff here
}
as explained in this answer
JSONObject has the keys() method that returns an Iterator<String>. Through the iterator you can retrieve the value associated with each key. Here the documentation
EDIT:
Since you are using GSON , you can retrieve the keys through the method entrySet()
You should use Iterator, which you can get by calling .keys() on your JSONObject. I think something like that should work (using org.json library):
String[] output = new String[jsonObject.length()];
Iterator iterator = jsonObject.keys();
int i = 0;
while (iterator.hasNext()){
output[i++] = jsonObject.optString((String) iterator.next());
}
EDIT Ok, in case of GSON it will be like this:
Set<Map.Entry<String, JsonElement>> set = jsonObject.entrySet();
String[] out = new String[set.size()];
int i = 0;
for (Map.Entry<String, JsonElement> x : set){
out[i++] = x.getValue().toString();
}
If you are using gson then simple solution is :
Type mapType = new TypeToken<Map<String, String>>(){}.getType();
Map<String, String> map = gson.fromJson(YOUR_JSON_STRING, mapType);
// get only values from map
Collection<String> values = map.values();
for (String string : values) {
// do your stuff here
}
result values collection contains
[cat, 4, 2]
JSONObject jsonObject = new JSONObject(parentJson.getJSONObject("objectname")
.toString());
Iterator<?> iter = jsonObject.keys();
while (iter.hasNext()) {
String key =(String) iter.next();
String value = jsonObject.getString(key);
}

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 storing arraylist data into multimap using same key

Hi friends i got stucked into these problem at the last stage of my program.Here is some description about my project:i am calling a web service with the help of Ksoap and getting the JSON response from the server than,i am parsed that response and store it into the correspondent arraylist.Till here everything is working fine.Now the problem starts here i want to store all these AppID,AppName,AppTabID,Icon,Tabname into a multimap with same key for the same index.How can i achieve that ?Any help would highly appreciated!
private SoapPrimitive response;
ArrayList<String> AppID = new ArrayList<String>();
ArrayList<String> AppName = new ArrayList<String>();
ArrayList<String> AppTabId = new ArrayList<String>();
ArrayList<String> Icon = new ArrayList<String>();
ArrayList<Drawable> drawables=new ArrayList<Drawable>();
ArrayList<String> TabName = new ArrayList<String>();
<!--here are the Arraylist declaration->
public String parse(String a) throws Exception {
JSONArray jsonArry1 = new JSONArray(res); // create a json object from a string
// JSONArray jsonEvents = jsonObj.optJSONArray("AppItems"); // get all events as json objects from AppItems array
System.out.println("Length of array for AppItem tag is.. "+jsonArry1.length());
for(int i = 0; i < jsonArry1.length(); i++){
JSONObject event = jsonArry1.getJSONObject(i); // create a single event jsonObject
String AppID=event.getString("AppId");
System.out.println("AppId is "+AppID);
String AppName=event.getString("AppName");
System.out.println("AppName is "+AppName);
String AppTabId=event.getString("AppTabId");
System.out.println("AppTabId is "+AppTabId);
String Icon=event.getString("Icon");
System.out.println("Icon is "+Icon);
TabHtml=event.getString("TabHtml");
System.out.println("TabHtml = "+TabHtml);
}
System.out.println("return"+TabHtml);
return TabHtml;
}
the above code i am using for saving all the content into arraylist object.From here i want to set all these diferent Arraylist into same MultiMap.How can i achieve that?
I'd just define an AppData container class to hold all data related to a single response, and then just put AppData objects into your multimap.
On this link (Java Map Interface) search for multimap which gives a straight forward implementation of a multimap.
However from what I understand of your question, you'll have to put all your Lists into a List and that would go into a MultiMap (which will just be a HashMap<String,ArrayList<ArrayList>>).
It is not very good approach to have all these different lists for different fields in response, but as you have implemented almost completed, I would lead this approach further:
You can have a Map into map to resolve this prob:
All you need to have follow the below loop:
HashMap<Integer, HashMap<String, String> parsed=new HashMap<Integer, HashMap<String, String>();
for(int i=0;i<AppID.size();i++)
{
HashMap<String, String> keyValues= new HashMap<String, String>();
keyValues.put("id", AppName .get(0));
keyValues.put("id", AppTabId .get(0));
keyValues.put("id", Icon .get(0));
.....
parsed(new Integer(i), keyValues);
}

Deserialize JSON with Gson in an object

I have a JSON string such as below. That comes from a Website (the URL outputs below to a page) which I'm using in an android application.
{"posts": [{"id":"0000001","longitude":"50.722","latitude":"-1.87817","position":"Someplace 1","altitude":"36","description":"Some place 1 "},{"id":"0000002","longitude":"50.722","latitude":"-1.87817","position":"Some PLace 2","altitude":"36","description":"Some place 2 description"}]}
I would like to deserialize this into a List where I can iterate through them later on the application. How do I do this? I have created a class with properties and methods and a List class as below and then using fromJson to deserialize it, but it returns NULL. Hope the question is clear and many thanks in advance.
ListClass
package dataaccess;
import java.util.List;
public class LocationList {
public static List<Location> listLocations;
public void setLocationList(List <Location> listLocations) {
LocationList.listLocations = listLocations;
}
public List<Location> getLocationList() {
return listLocations;
}
}
GSON
public LocationList[] getJsonFromGson(String jsonURL) throws IOException{
URL url = new URL(jsonURL);
String content = IOUtils.toString(new InputStreamReader(url.openStream()));
LocationList[] locations = new Gson().fromJson(content, LocationList[].class);
return locations;
}
You try to deserialize into an array of LocationList objects - that surely wasn't your intent, was it? The json snippet doesn't contain a list of lists.
I would drop the class LocationList (except it ought to be extened in future?), and use a pure List. Then, you have to create a type token like this:
java.lang.reflect.Type type = new com.google.gson.reflect.TypeToken<ArrayList<Location>>() {}.getType();
List<Location> locations = new Gson().fromJson(content, type);
What if this JSON response can be parsed using native classes, here is a solution for the same:
String strJsonResponse="Store response here";
JsonObject obj = new JsonObject(strJsonResponse);
JsonArray array = obj.getJsonArray("posts");
for(int i=0; i<array.length; i++)
{
JsonObject subObj = array.getJsonObject(i);
String id = subObj.getString("id");
String longitude = subObj.getString("longitude");
String latitude = subObj.getString("latitude");
String position = subObj.getString("position");
String altitude = subObj.getString("altitude");
String description = subObj.getString("description");
// do whatever procedure you want to do here
}

Categories

Resources