Looping through Multiple JSON Objects in Android - java

I'm trying to parse a JSON object, part of which looks like this :
{
"status":{
"rcode":200,
"message":"OK"
},
"data":{
"0":{
"SubFranchiseID":"0",
"OutletID":"607",
"OutletName":"Spill ",
"BrandID":"403",
"Address":"J-349, JP Road, Opp. Apna Bazar, JP Rd, D.N.Nagar, Andheri West, Mumbai, Maharashtra, India",
"NeighbourhoodID":"1",
"CityID":"1",
"Email":null,
"Timings":"Everyday: 6 pm to 1:30 am.",
"CityRank":null,
"Latitude":"19.127473",
"Longitude":"72.832545",
"Pincode":null,
"Landmark":null,
"Streetname":null,
"BrandName":"Spill ",
"OutletURL":"https:\/\/plus.google.com\/111539701326240643109\/about?hl=en-US",
"NumCoupons":1,
"NeighbourhoodName":"Andheri West",
"PhoneNumber":"+91 22 2642 5895",
"CityName":"Mumbai",
"Distance":8205.2235,
"Categories":[
{
"OfflineCategoryID":"32",
"Name":"Continental",
"ParentCategoryID":"1",
"CategoryType":"Cuisine"
},
{
"OfflineCategoryID":"13",
"Name":"Bar and Restaurant",
"ParentCategoryID":"1",
"CategoryType":"TypeOfRestaurant"
},
{
"OfflineCategoryID":"17",
"Name":"Italian",
"ParentCategoryID":"1",
"CategoryType":"Cuisine"
},
{
"OfflineCategoryID":"1",
"Name":"Restaurant",
"ParentCategoryID":null,
"CategoryType":""
},
{
"OfflineCategoryID":"21",
"Name":"North Indian",
"ParentCategoryID":"1",
"CategoryType":"Cuisine"
}
],
"LogoURL":"http:\/\/www.google.in\/sitespecific\/media\/generated\/offlineimages\/logo_403.jpg",
"CoverURL":"http:\/\/www.google.in\/sitespecific\/media\/generated\/offlineimages\/cover_607.jpg"
},
"1 "{
"SubFranchiseID":"1",
"OutletID":"60",
"OutletName":"Bill ",
.
.
.
}
}
There are nearly 35 Json objects and nested JsonArrays for each of these objects.I'm trying to get data like this :
url = new URL(uri);
URLConnection connection = url.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
reader.close();
json =sb.toString();
JSONObject sjson=json.getJSONObject("data");
Log.d("sjson values-->",sjson+"--");
**JSONObject ssjson=sjson.getJSONObject("0");**
And now i am getting each of values like this :
String outletName = ssjson.getString("OutletName");
My question is there any better way (loop) through all objects ( 0,1,...35) and get data for each individual object separately.

Example json
{
"status": {
"rcode": "200",
"message": "Good, you got me!!!"
},
"data": [
{
"SubFranchiseID": "0",
"OutletID": "607",
"OutletName": "Spill",
},
{
"SubFranchiseID": "0",
"OutletID": "607",
"OutletName": "Spill"
}
]
}
Represent the json in terms of plain java classes with getter and
setters
First create a the root class (for the root object)
public class Root {
//For the status object
private Status status;
//For the array of data objects
private List<Data> data;
//create setters and getters for the two properties.
}
public class Status {
private String rcode;
//this maps to the rcode in the status object in json
private String message;
//create setters and getters for the two
}
public class Data {
private String SubFranchiseID;
private String OutletID;
private String OutletName;
//create setters and getters for these properties.
}
Now, lets do the magic with gson (The serialization of the json in to the ready made classes)
reader.close();
json =sb.toString();
Root root = new Gson().fromJson(response, Root.class);
//get the rcode
if(root.getStatus().getrCode().equalsIgnoreCase("200"))
{
//print the data.
for(Data d : root.getData()) {
System.out.println(d.getSubFranchiseID()+"-"+d.getOutletID()+"-"+d.getOutletName());
}
}
A small note for using gson.
1.) The property names inside the classes should match the property in the json or else use a `#SerializeName("propertyname")`.
2.) An array of objects would map to List<YourObject> , for eg : the data property in the json.
3.) You can have default value for your properties without creating getters and setters for them like
private boolean isJson = true;

Thanks for the help. I have a lot of json objects inside "data" -> "0" like "Outletname","OutletID ",etc , before Json Array ( "Categories" ). i have created a model class for my data. Now i want to itterate json objects data using Gson.Part of my json data
"0":{
"SubFranchiseID":"0",
"OutletID":"607",
"OutletName":"Spill ",
"BrandID":"403",
"Address":"J-349, JP Road, Opp. Apna Bazar, JP Rd, D.N.Nagar, Andheri West, Mumbai, Maharashtra, India",
"NeighbourhoodID":"1",
"CityID":"1",
"Email":null,
"Timings":"Everyday: 6 pm to 1:30 am.",
"CityRank":null,
"Latitude":"19.127473",
"Longitude":"72.832545",
"Pincode":null,
"Landmark":null,
"Streetname":null,
"BrandName":"Spill ",
"OutletURL":"https:\/\/plus.google.com\/111539701326240643109\/about?hl=en-US",
"NumCoupons":1,
"NeighbourhoodName":"Andheri West",
"PhoneNumber":"+91 22 2642 5895",
"CityName":"Mumbai",
"Distance":8205.2235,
"Categories":[
{
"OfflineCategoryID":"32",
"Name":"Continental",
"ParentCategoryID":"1",
"CategoryType":"Cuisine"
},
{
"OfflineCategoryID":"13",
"Name":"Bar and Restaurant",
"ParentCategoryID":"1",
"CategoryType":"TypeOfRestaurant"
},
{
"OfflineCategoryID":"17",
"Name":"Italian",
"ParentCategoryID":"1",
"CategoryType":"Cuisine"
},
{
"OfflineCategoryID":"1",
"Name":"Restaurant",
"ParentCategoryID":null,
"CategoryType":""
},
{
"OfflineCategoryID":"21",
"Name":"North Indian",
"ParentCategoryID":"1",
"CategoryType":"Cuisine"
}
],
"LogoURL":"http:\/\/www.google.in\/sitespecific\/media\/generated\/offlineimages\/logo_403.jpg",
"CoverURL":"http:\/\/www.google.in\/sitespecific\/media\/generated\/offlineimages\/cover_607.jpg"
},
}
My java Model Class :
/**
* SubFranchiseID : 0
* OutletID : 607
* OutletName : Spill
* BrandID : 403
* Address : J-349, JP Road, Opp. Apna Bazar, JP Rd, D.N.Nagar, Andheri West, Mumbai, Maharashtra, India
* NeighbourhoodID : 1
* CityID : 1
* Email : null
* Timings : Everyday: 6 pm to 1:30 am.
* CityRank : null
* Latitude : 19.127473
* Longitude : 72.832545
* Pincode : null
* Landmark : null
* Streetname : null
* BrandName : Spill
* OutletURL : https://plus.google.com/111539701326240643109/about?hl=en-US
* NumCoupons : 1
* NeighbourhoodName : Andheri West
* PhoneNumber : +91 22 2642 5895
* CityName : Mumbai
* Distance : 8205.2235
* Categories : [{"OfflineCategoryID":"32","Name":"Continental","ParentCategoryID":"1","CategoryType":"Cuisine"},{"OfflineCategoryID":"13","Name":"Bar and Restaurant","ParentCategoryID":"1","CategoryType":"TypeOfRestaurant"},{"OfflineCategoryID":"17","Name":"Italian","ParentCategoryID":"1","CategoryType":"Cuisine"},{"OfflineCategoryID":"1","Name":"Restaurant","ParentCategoryID":null,"CategoryType":""},{"OfflineCategoryID":"21","Name":"North Indian","ParentCategoryID":"1","CategoryType":"Cuisine"}]
* LogoURL : http://www.google.in/sitespecific/media/generated/offlineimages/logo_403.jpg
* CoverURL : http://www.google.in/sitespecific/media/generated/offlineimages/cover_607.jpg
*/
public static class OutletDetailsEntity {
private String SubFranchiseID;
private String OutletID;
private String OutletName;
private String BrandID;
private String Address;
private String NeighbourhoodID;
private String CityID;
private Object Email;
private String Timings;
private Object CityRank;
private String Latitude;
private String Longitude;
private Object Pincode;
private Object Landmark;
private Object Streetname;
private String BrandName;
private String OutletURL;
private int NumCoupons;
private String NeighbourhoodName;
private String PhoneNumber;
private String CityName;
private double Distance;
private String LogoURL;
private String CoverURL;
private List<CategoriesEntity> Categories;
public void setSubFranchiseID(String SubFranchiseID) {
this.SubFranchiseID = SubFranchiseID;
}
public void setOutletID(String OutletID) {
this.OutletID = OutletID;
}
public void setOutletName(String OutletName) {
this.OutletName = OutletName;
}
public void setBrandID(String BrandID) {
this.BrandID = BrandID;
}
public void setAddress(String Address) {
this.Address = Address;
}
public void setNeighbourhoodID(String NeighbourhoodID) {
this.NeighbourhoodID = NeighbourhoodID;
}
public void setCityID(String CityID) {
this.CityID = CityID;
}
public void setEmail(Object Email) {
this.Email = Email;
}
public void setTimings(String Timings) {
this.Timings = Timings;
}
public void setCityRank(Object CityRank) {
this.CityRank = CityRank;
}
public void setLatitude(String Latitude) {
this.Latitude = Latitude;
}
public void setLongitude(String Longitude) {
this.Longitude = Longitude;
}
public void setPincode(Object Pincode) {
this.Pincode = Pincode;
}
public void setLandmark(Object Landmark) {
this.Landmark = Landmark;
}
public void setStreetname(Object Streetname) {
this.Streetname = Streetname;
}
public void setBrandName(String BrandName) {
this.BrandName = BrandName;
}
public void setOutletURL(String OutletURL) {
this.OutletURL = OutletURL;
}
public void setNumCoupons(int NumCoupons) {
this.NumCoupons = NumCoupons;
}
public void setNeighbourhoodName(String NeighbourhoodName) {
this.NeighbourhoodName = NeighbourhoodName;
}
public void setPhoneNumber(String PhoneNumber) {
this.PhoneNumber = PhoneNumber;
}
public void setCityName(String CityName) {
this.CityName = CityName;
}
public void setDistance(double Distance) {
this.Distance = Distance;
}
public void setLogoURL(String LogoURL) {
this.LogoURL = LogoURL;
}
public void setCoverURL(String CoverURL) {
this.CoverURL = CoverURL;
}
public void setCategories(List<CategoriesEntity> Categories) {
this.Categories = Categories;
}
public String getSubFranchiseID() {
return SubFranchiseID;
}
public String getOutletID() {
return OutletID;
}
public String getOutletName() {
return OutletName;
}
public String getBrandID() {
return BrandID;
}
public String getAddress() {
return Address;
}
public String getNeighbourhoodID() {
return NeighbourhoodID;
}
public String getCityID() {
return CityID;
}
public Object getEmail() {
return Email;
}
public String getTimings() {
return Timings;
}
public Object getCityRank() {
return CityRank;
}
public String getLatitude() {
return Latitude;
}
public String getLongitude() {
return Longitude;
}
public Object getPincode() {
return Pincode;
}
public Object getLandmark() {
return Landmark;
}
public Object getStreetname() {
return Streetname;
}
public String getBrandName() {
return BrandName;
}
public String getOutletURL() {
return OutletURL;
}
public int getNumCoupons() {
return NumCoupons;
}
public String getNeighbourhoodName() {
return NeighbourhoodName;
}
public String getPhoneNumber() {
return PhoneNumber;
}
public String getCityName() {
return CityName;
}
public double getDistance() {
return Distance;
}
public String getLogoURL() {
return LogoURL;
}
public String getCoverURL() {
return CoverURL;
}

Related

Iterating/Getting JSONObject inside of JSONArray without key

Need to get the Every JSONObject inside this JSONArray. Currently there is only 2 JSONObjects are there but there will be more in the future. So, i need to make it dynamic based on length of the JSONArray.
Here is the whole JSON:
{
"data": [
{
"previous_class_percentage": 58.0,
"speech_disabilty": true,
"hearing_difficulty": false,
"last_name": "Krishnana",
"weight": 54.0,
"submitted_timestamp": "2018-02-15T10:22:00Z",
"id_number": "VS017BH0004"
},
{
"previous_class_percentage": 88.0,
"speech_disabilty": true,
"hearing_difficulty": false,
"last_name": "Krishnana",
"weight": 54.0,
"submitted_timestamp": "2018-02-14T10:22:00Z",
"id_number": "VS017BH0006"
}
]
}
I am trying something like this
try {
int k = 0;
while (i<sectionJsonArr.length()){
JSONObject data = sectionJsonArr.optJSONObject(k);
Log.d("json-array",data+"");
String b_certificate_no = data.getString("id_number");
if (student_birth_certfct_number.equals(b_certificate_no)){
Log.d("text","inside if");
//TO-DO CODE
}
k++;
}
}catch (JSONException e){
e.printStackTrace();
}
try{
for( int i=0; i < sectionJsonArr.length(); i++){
JSONObject data = obj.optJSONObject(i);
Log.d("json-array",data+"");
String b_certificate_no = data.getString("id_number");
if (student_birth_certfct_number.equals(b_certificate_no)){
Log.d("text","inside if");
//TO-DO CODE
}
}
}catch(JSONException e){
e.printStackTrace();
}
this is also a way to do that
Step-1: integrate below the library.
implementation 'com.google.code.gson:gson:2.8.5'
Step-2: copy below POJO class.
public class Example {
#SerializedName("data")
#Expose
private ArrayList<Datum> data = null;
public ArrayList<Datum> getData() {
return data;
}
public void setData(ArrayList<Datum> data) {
this.data = data;
}
public class Datum {
#SerializedName("previous_class_percentage")
#Expose
private Double previousClassPercentage;
#SerializedName("speech_disabilty")
#Expose
private Boolean speechDisabilty;
#SerializedName("hearing_difficulty")
#Expose
private Boolean hearingDifficulty;
#SerializedName("last_name")
#Expose
private String lastName;
#SerializedName("weight")
#Expose
private Double weight;
#SerializedName("submitted_timestamp")
#Expose
private String submittedTimestamp;
#SerializedName("id_number")
#Expose
private String idNumber;
public Double getPreviousClassPercentage() {
return previousClassPercentage;
}
public void setPreviousClassPercentage(Double previousClassPercentage) {
this.previousClassPercentage = previousClassPercentage;
}
public Boolean getSpeechDisabilty() {
return speechDisabilty;
}
public void setSpeechDisabilty(Boolean speechDisabilty) {
this.speechDisabilty = speechDisabilty;
}
public Boolean getHearingDifficulty() {
return hearingDifficulty;
}
public void setHearingDifficulty(Boolean hearingDifficulty) {
this.hearingDifficulty = hearingDifficulty;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Double getWeight() {
return weight;
}
public void setWeight(Double weight) {
this.weight = weight;
}
public String getSubmittedTimestamp() {
return submittedTimestamp;
}
public void setSubmittedTimestamp(String submittedTimestamp) {
this.submittedTimestamp = submittedTimestamp;
}
public String getIdNumber() {
return idNumber;
}
public void setIdNumber(String idNumber) {
this.idNumber = idNumber;
}
}
}
Step-3: Parse response.
// "response" String that you will get from server or other.
Example example = new Gson().fromJson(response,Example.class);
for (Example.Datum response: example.getData()) {
String b_certificate_no = response.getIdNumber();
}

Creating list of POJOs when the JSON only has objects

I'm using Pocket API to get a list of bookmarked articles and their URLs, there are hundreds, here is a sample with only 2 articles:
{
"status": 1,
"complete": 1,
"list": {
"734233858": {
"item_id": "734233858",
"resolved_id": "734233858",
"given_url": "https://blog.openshift.com/developing-single-page-web-applications-using-java-8-spark-mongodb-and-angularjs/",
"given_title": "",
"favorite": "0",
"status": "0",
"time_added": "1466459879",
"time_updated": "1466459862",
"time_read": "0",
"time_favorited": "0",
"sort_id": 1,
"resolved_title": "Developing Single Page Web Applications using Java 8, Spark, MongoDB, and AngularJS",
"resolved_url": "https://blog.openshift.com/developing-single-page-web-applications-using-java-8-spark-mongodb-and-angularjs/",
"excerpt": "In this post you will learn how to use a micro framework called Spark to build a RESTful backend. The RESTful backend is consumed by a single page web application using AngularJS and MongoDB for data storage. I’ll also show you how to run Java 8 on OpenShift.",
"is_article": "1",
"is_index": "0",
"has_video": "0",
"has_image": "1",
"word_count": "2727"
},
"1015284226": {
"item_id": "1015284226",
"resolved_id": "1015284226",
"given_url": "https://sparktutorials.github.io/2015/08/04/spark-video-tutorials.html",
"given_title": "",
"favorite": "0",
"status": "0",
"time_added": "1466458750",
"time_updated": "1466458737",
"time_read": "0",
"time_favorited": "0",
"sort_id": 0,
"resolved_title": "Spark Video Tutorials",
"resolved_url": "http://sparktutorials.github.io/2015/08/04/spark-video-tutorials.html",
"excerpt": "Our friends over at learnhowtoprogram.com have been working on a series of Java courses for beginners, all of which feature Spark. This post contains an overview of these courses with direct links to their videos.",
"is_article": "1",
"is_index": "0",
"has_video": "0",
"has_image": "0",
"word_count": "41"
}
},
"error": null,
"search_meta": {
"search_type": "normal"
},
"since": 1509309762
}
As you can see the "list": {} has many items, but it's an array, it contains objects. So when I try to generate the POJOs using http://www.jsonschema2pojo.org I get POJOS named after each item's ID :
package model;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class _1015284226 {
#SerializedName("item_id")
#Expose
private String itemId;
#SerializedName("resolved_id")
#Expose
private String resolvedId;
#SerializedName("given_url")
#Expose
private String givenUrl;
#SerializedName("given_title")
#Expose
private String givenTitle;
#SerializedName("favorite")
#Expose
private String favorite;
#SerializedName("status")
#Expose
private String status;
#SerializedName("time_added")
#Expose
private String timeAdded;
#SerializedName("time_updated")
#Expose
private String timeUpdated;
#SerializedName("time_read")
#Expose
private String timeRead;
#SerializedName("time_favorited")
#Expose
private String timeFavorited;
#SerializedName("sort_id")
#Expose
private Integer sortId;
#SerializedName("resolved_title")
#Expose
private String resolvedTitle;
#SerializedName("resolved_url")
#Expose
private String resolvedUrl;
#SerializedName("excerpt")
#Expose
private String excerpt;
#SerializedName("is_article")
#Expose
private String isArticle;
#SerializedName("is_index")
#Expose
private String isIndex;
#SerializedName("has_video")
#Expose
private String hasVideo;
#SerializedName("has_image")
#Expose
private String hasImage;
#SerializedName("word_count")
#Expose
private String wordCount;
/**
* No args constructor for use in serialization
*
*/
public _1015284226() {
}
/**
*
* #param hasImage
* #param givenUrl
* #param status
* #param timeFavorited
* #param isIndex
* #param excerpt
* #param resolvedId
* #param sortId
* #param givenTitle
* #param timeUpdated
* #param isArticle
* #param wordCount
* #param itemId
* #param favorite
* #param timeAdded
* #param hasVideo
* #param resolvedUrl
* #param resolvedTitle
* #param timeRead
*/
public _1015284226(String itemId, String resolvedId, String givenUrl, String givenTitle, String favorite, String status, String timeAdded, String timeUpdated, String timeRead, String timeFavorited, Integer sortId, String resolvedTitle, String resolvedUrl, String excerpt, String isArticle, String isIndex, String hasVideo, String hasImage, String wordCount) {
super();
this.itemId = itemId;
this.resolvedId = resolvedId;
this.givenUrl = givenUrl;
this.givenTitle = givenTitle;
this.favorite = favorite;
this.status = status;
this.timeAdded = timeAdded;
this.timeUpdated = timeUpdated;
this.timeRead = timeRead;
this.timeFavorited = timeFavorited;
this.sortId = sortId;
this.resolvedTitle = resolvedTitle;
this.resolvedUrl = resolvedUrl;
this.excerpt = excerpt;
this.isArticle = isArticle;
this.isIndex = isIndex;
this.hasVideo = hasVideo;
this.hasImage = hasImage;
this.wordCount = wordCount;
}
public String getItemId() {
return itemId;
}
public void setItemId(String itemId) {
this.itemId = itemId;
}
public String getResolvedId() {
return resolvedId;
}
public void setResolvedId(String resolvedId) {
this.resolvedId = resolvedId;
}
public String getGivenUrl() {
return givenUrl;
}
public void setGivenUrl(String givenUrl) {
this.givenUrl = givenUrl;
}
public String getGivenTitle() {
return givenTitle;
}
public void setGivenTitle(String givenTitle) {
this.givenTitle = givenTitle;
}
public String getFavorite() {
return favorite;
}
public void setFavorite(String favorite) {
this.favorite = favorite;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getTimeAdded() {
return timeAdded;
}
public void setTimeAdded(String timeAdded) {
this.timeAdded = timeAdded;
}
public String getTimeUpdated() {
return timeUpdated;
}
public void setTimeUpdated(String timeUpdated) {
this.timeUpdated = timeUpdated;
}
public String getTimeRead() {
return timeRead;
}
public void setTimeRead(String timeRead) {
this.timeRead = timeRead;
}
public String getTimeFavorited() {
return timeFavorited;
}
public void setTimeFavorited(String timeFavorited) {
this.timeFavorited = timeFavorited;
}
public Integer getSortId() {
return sortId;
}
public void setSortId(Integer sortId) {
this.sortId = sortId;
}
public String getResolvedTitle() {
return resolvedTitle;
}
public void setResolvedTitle(String resolvedTitle) {
this.resolvedTitle = resolvedTitle;
}
public String getResolvedUrl() {
return resolvedUrl;
}
public void setResolvedUrl(String resolvedUrl) {
this.resolvedUrl = resolvedUrl;
}
public String getExcerpt() {
return excerpt;
}
public void setExcerpt(String excerpt) {
this.excerpt = excerpt;
}
public String getIsArticle() {
return isArticle;
}
public void setIsArticle(String isArticle) {
this.isArticle = isArticle;
}
public String getIsIndex() {
return isIndex;
}
public void setIsIndex(String isIndex) {
this.isIndex = isIndex;
}
public String getHasVideo() {
return hasVideo;
}
public void setHasVideo(String hasVideo) {
this.hasVideo = hasVideo;
}
public String getHasImage() {
return hasImage;
}
public void setHasImage(String hasImage) {
this.hasImage = hasImage;
}
public String getWordCount() {
return wordCount;
}
public void setWordCount(String wordCount) {
this.wordCount = wordCount;
}
}
the List POJO which contains the items was created as:
package model;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class List {
#SerializedName("1015284226")
#Expose
private model._1015284226 _1015284226;
/**
* No args constructor for use in serialization
*
*/
public List() {
}
/**
*
* #param _1015284226
*/
public List(model._1015284226 _1015284226) {
super();
this._1015284226 = _1015284226;
}
public model._1015284226 get1015284226() {
return _1015284226;
}
public void set1015284226(model._1015284226 _1015284226) {
this._1015284226 = _1015284226;
}
}
which is obviously giving me issues when I try to parse the JSON
I'm using retrofit 2 .
I'm thinking I should refactor the List POJO so it contains an ArrayList of items, but don't want to fiddle too much with what was automatically generated for me.
You can do it manually like this.
JSONObject jsonObj = new JSONObject(json);
JSONObject lists= jsonObj.getJSONObject("list");
Iterator x = lists.keys();
JSONArray jsonArray = new JSONArray();
while (x.hasNext()){
String key = (String) x.next();
jsonArray.put(lists.get(key));
}
jsonArray is your list.
After that, you may parse JSON to object.

Storing JSON object using Volley

This is the structure of the JSON I need to Load,
{
"readme_0" : "THIS JSON IS THE RESULT OF YOUR SEARCH QUERY - THERE IS NO WEB PAGE WHICH SHOWS THE RESULT!",
"readme_1" : "loklak.org is the framework for a message search system, not the portal, read: http://loklak.org/about.html#notasearchportal",
"readme_2" : "This is supposed to be the back-end of a search portal. For the api, see http://loklak.org/api.html",
"readme_3" : "Parameters q=(query), source=(cache|backend|twitter|all), callback=p for jsonp, maximumRecords=(message count), minified=(true|false)",
"search_metadata" : {
"itemsPerPage" : "100",
"count" : "100",
"count_twitter_all" : 0,
"count_twitter_new" : 100,
"count_backend" : 0,
"count_cache" : 78780,
"hits" : 78780,
"period" : 3066,
"query" : "apple",
"client" : "180.215.121.78",
"time" : 5219,
"servicereduction" : "false",
"scraperInfo" : "http://45.55.245.191:9000,local"
},
"statuses" : [ {
"created_at" : "2016-01-09T12:11:38.000Z",
"screen_name" : "arifazmi92",
"text" : "Perhaps I shouldn't have eaten that pisang goreng cheese perisa green apple. <img class=\"Emoji Emoji--forText\" src=\"https://abs.twimg.com/emoji/v2/72x72/1f605.png\" draggable=\"false\" alt=\"😅\" title=\"Smiling face with open mouth and cold sweat\" aria-label=\"Emoji: Smiling face with open mouth and cold sweat\"><img class=\"Emoji Emoji--forText\" src=\"https://abs.twimg.com/emoji/v2/72x72/1f605.png\" draggable=\"false\" alt=\"😅\" title=\"Smiling face with open mouth and cold sweat\" aria-label=\"Emoji: Smiling face with open mouth and cold sweat\"><img class=\"Emoji Emoji--forText\" src=\"https://abs.twimg.com/emoji/v2/72x72/1f605.png\" draggable=\"false\" alt=\"😅\" title=\"Smiling face with open mouth and cold sweat\" aria-label=\"Emoji: Smiling face with open mouth and cold sweat\">",
"link" : "https://twitter.com/arifazmi92/status/685796067082813440",
"id_str" : "685796067082813440",
"source_type" : "TWITTER",
"provider_type" : "SCRAPED",
"retweet_count" : 0,
"favourites_count" : 0,
"images" : [ ],
"images_count" : 0,
"audio" : [ ],
"audio_count" : 0,
"videos" : [ ],
"videos_count" : 0,
"place_name" : "Bandar Shah Alam, Selangor",
"place_id" : "9be3b0eca6c21f6c",
"place_context" : "FROM",
"place_country" : "Malaysia",
"place_country_code" : "MY",
"place_country_center" : [ -59.30559537806809, 3.4418498787292435 ],
"location_point" : [ 101.53280621465888, 3.0850698533863863 ],
"location_radius" : 0,
"location_mark" : [ 101.52542227271437, 3.0911033774188725 ],
"location_source" : "PLACE",
"hosts" : [ "abs.twimg.com" ],
"hosts_count" : 1,
"links" : [ "https://abs.twimg.com/emoji/v2/72x72/1f605.png\"", "https://abs.twimg.com/emoji/v2/72x72/1f605.png\"", "https://abs.twimg.com/emoji/v2/72x72/1f605.png\"" ],
"links_count" : 3,
"mentions" : [ ],
"mentions_count" : 0,
"hashtags" : [ ],
"hashtags_count" : 0,
"without_l_len" : 626,
"without_lu_len" : 626,
"without_luh_len" : 626,
"user" : {
"screen_name" : "arifazmi92",
"user_id" : "44503967",
"name" : "Arif Azmi",
"profile_image_url_https" : "https://pbs.twimg.com/profile_images/685788990004301824/NbFnnLuO_bigger.jpg",
"appearance_first" : "2016-01-09T12:11:57.933Z",
"appearance_latest" : "2016-01-09T12:11:57.933Z"
}
}
} ],
"aggregations" : { }
}
And these are my POJO classes that I've generated:
MainPojo.class
public class MainPojo
{
#SerializedName("readme_0")
#Expose
private String readme0;
#SerializedName("readme_1")
#Expose
private String readme1;
#SerializedName("readme_2")
#Expose
private String readme2;
#SerializedName("readme_3")
#Expose
private String readme3;
#SerializedName("search_metadata")
#Expose
private SearchMetadata searchMetadata;
#SerializedName("statuses")
#Expose
private List<Status> statuses = new ArrayList<Status>();
#SerializedName("aggregations")
#Expose
private Aggregations aggregations;
public String getReadme0() {
return readme0;
}
public void setReadme0(String readme0) {
this.readme0 = readme0;
}
public String getReadme1() {
return readme1;
}
public void setReadme1(String readme1) {
this.readme1 = readme1;
}
public String getReadme2() {
return readme2;
}
public void setReadme2(String readme2) {
this.readme2 = readme2;
}
public String getReadme3() {
return readme3;
}
public void setReadme3(String readme3) {
this.readme3 = readme3;
}
public SearchMetadata getSearchMetadata() {
return searchMetadata;
}
public void setSearchMetadata(SearchMetadata searchMetadata) {
this.searchMetadata = searchMetadata;
}
public List<Status> getStatuses() {
return statuses;
}
public void setStatuses(List<Status> statuses) {
this.statuses = statuses;
}
public Aggregations getAggregations() {
return aggregations;
}
public void setAggregations(Aggregations aggregations) {
this.aggregations = aggregations;
}
}
Status.class
public class Status
{
#SerializedName("created_at")
#Expose
private String createdAt;
#SerializedName("screen_name")
#Expose
private String screenName;
#SerializedName("text")
#Expose
private String text;
#SerializedName("link")
#Expose
private String link;
#SerializedName("id_str")
#Expose
private String idStr;
#SerializedName("source_type")
#Expose
private String sourceType;
#SerializedName("provider_type")
#Expose
private String providerType;
#SerializedName("retweet_count")
#Expose
private Integer retweetCount;
#SerializedName("favourites_count")
#Expose
private Integer favouritesCount;
#SerializedName("images")
#Expose
private List<Object> images = new ArrayList<Object>();
#SerializedName("images_count")
#Expose
private Integer imagesCount;
#SerializedName("audio")
#Expose
private List<Object> audio = new ArrayList<Object>();
#SerializedName("audio_count")
#Expose
private Integer audioCount;
#SerializedName("videos")
#Expose
private List<Object> videos = new ArrayList<Object>();
#SerializedName("videos_count")
#Expose
private Integer videosCount;
#SerializedName("place_name")
#Expose
private String placeName;
#SerializedName("place_id")
#Expose
private String placeId;
#SerializedName("place_context")
#Expose
private String placeContext;
#SerializedName("location_point")
#Expose
private List<Double> locationPoint = new ArrayList<Double>();
#SerializedName("location_radius")
#Expose
private Integer locationRadius;
#SerializedName("location_mark")
#Expose
private List<Double> locationMark = new ArrayList<Double>();
#SerializedName("location_source")
#Expose
private String locationSource;
#SerializedName("hosts")
#Expose
private List<String> hosts = new ArrayList<String>();
#SerializedName("hosts_count")
#Expose
private Integer hostsCount;
#SerializedName("links")
#Expose
private List<String> links = new ArrayList<String>();
#SerializedName("links_count")
#Expose
private Integer linksCount;
#SerializedName("mentions")
#Expose
private List<Object> mentions = new ArrayList<Object>();
#SerializedName("mentions_count")
#Expose
private Integer mentionsCount;
#SerializedName("hashtags")
#Expose
private List<Object> hashtags = new ArrayList<Object>();
#SerializedName("hashtags_count")
#Expose
private Integer hashtagsCount;
#SerializedName("without_l_len")
#Expose
private Integer withoutLLen;
#SerializedName("without_lu_len")
#Expose
private Integer withoutLuLen;
#SerializedName("without_luh_len")
#Expose
private Integer withoutLuhLen;
#SerializedName("user")
#Expose
private User user;
#SerializedName("provider_hash")
#Expose
private String providerHash;
#SerializedName("classifier_language")
#Expose
private String classifierLanguage;
#SerializedName("classifier_language_probability")
#Expose
private Double classifierLanguageProbability;
public String getCreatedAt() {
return createdAt;
}
public void setCreatedAt(String createdAt) {
this.createdAt = createdAt;
}
public String getScreenName() {
return screenName;
}
public void setScreenName(String screenName) {
this.screenName = screenName;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getIdStr() {
return idStr;
}
public void setIdStr(String idStr) {
this.idStr = idStr;
}
public String getSourceType() {
return sourceType;
}
public void setSourceType(String sourceType) {
this.sourceType = sourceType;
}
public String getProviderType() {
return providerType;
}
public void setProviderType(String providerType) {
this.providerType = providerType;
}
public Integer getRetweetCount() {
return retweetCount;
}
public void setRetweetCount(Integer retweetCount) {
this.retweetCount = retweetCount;
}
public Integer getFavouritesCount() {
return favouritesCount;
}
public void setFavouritesCount(Integer favouritesCount) {
this.favouritesCount = favouritesCount;
}
public List<Object> getImages() {
return images;
}
public void setImages(List<Object> images) {
this.images = images;
}
public Integer getImagesCount() {
return imagesCount;
}
public void setImagesCount(Integer imagesCount) {
this.imagesCount = imagesCount;
}
public List<Object> getAudio() {
return audio;
}
public void setAudio(List<Object> audio) {
this.audio = audio;
}
public Integer getAudioCount() {
return audioCount;
}
public void setAudioCount(Integer audioCount) {
this.audioCount = audioCount;
}
public List<Object> getVideos() {
return videos;
}
public void setVideos(List<Object> videos) {
this.videos = videos;
}
public Integer getVideosCount() {
return videosCount;
}
public void setVideosCount(Integer videosCount) {
this.videosCount = videosCount;
}
public String getPlaceName() {
return placeName;
}
public void setPlaceName(String placeName) {
this.placeName = placeName;
}
public String getPlaceId() {
return placeId;
}
public void setPlaceId(String placeId) {
this.placeId = placeId;
}
public String getPlaceContext() {
return placeContext;
}
public void setPlaceContext(String placeContext) {
this.placeContext = placeContext;
}
public List<Double> getLocationPoint() {
return locationPoint;
}
public void setLocationPoint(List<Double> locationPoint) {
this.locationPoint = locationPoint;
}
public Integer getLocationRadius() {
return locationRadius;
}
public void setLocationRadius(Integer locationRadius) {
this.locationRadius = locationRadius;
}
public List<Double> getLocationMark() {
return locationMark;
}
public void setLocationMark(List<Double> locationMark) {
this.locationMark = locationMark;
}
public String getLocationSource() {
return locationSource;
}
public void setLocationSource(String locationSource) {
this.locationSource = locationSource;
}
public List<String> getHosts() {
return hosts;
}
public void setHosts(List<String> hosts) {
this.hosts = hosts;
}
public Integer getHostsCount() {
return hostsCount;
}
public void setHostsCount(Integer hostsCount) {
this.hostsCount = hostsCount;
}
public List<String> getLinks() {
return links;
}
public void setLinks(List<String> links) {
this.links = links;
}
public Integer getLinksCount() {
return linksCount;
}
public void setLinksCount(Integer linksCount) {
this.linksCount = linksCount;
}
public List<Object> getMentions() {
return mentions;
}
public void setMentions(List<Object> mentions) {
this.mentions = mentions;
}
public Integer getMentionsCount() {
return mentionsCount;
}
public void setMentionsCount(Integer mentionsCount) {
this.mentionsCount = mentionsCount;
}
public List<Object> getHashtags() {
return hashtags;
}
public void setHashtags(List<Object> hashtags) {
this.hashtags = hashtags;
}
public Integer getHashtagsCount() {
return hashtagsCount;
}
public void setHashtagsCount(Integer hashtagsCount) {
this.hashtagsCount = hashtagsCount;
}
public Integer getWithoutLLen() {
return withoutLLen;
}
public void setWithoutLLen(Integer withoutLLen) {
this.withoutLLen = withoutLLen;
}
public Integer getWithoutLuLen() {
return withoutLuLen;
}
public void setWithoutLuLen(Integer withoutLuLen) {
this.withoutLuLen = withoutLuLen;
}
public Integer getWithoutLuhLen() {
return withoutLuhLen;
}
public void setWithoutLuhLen(Integer withoutLuhLen) {
this.withoutLuhLen = withoutLuhLen;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String getProviderHash() {
return providerHash;
}
public void setProviderHash(String providerHash) {
this.providerHash = providerHash;
}
public String getClassifierLanguage() {
return classifierLanguage;
}
public void setClassifierLanguage(String classifierLanguage) {
this.classifierLanguage = classifierLanguage;
}
public Double getClassifierLanguageProbability() {
return classifierLanguageProbability;
}
public void setClassifierLanguageProbability(Double classifierLanguageProbability) {
this.classifierLanguageProbability = classifierLanguageProbability;
}
}
User.java
public class User {
#SerializedName("screen_name")
#Expose
private String screenName;
#SerializedName("user_id")
#Expose
private String userId;
#SerializedName("name")
#Expose
private String name;
#SerializedName("profile_image_url_https")
#Expose
private String profileImageUrlHttps;
#SerializedName("appearance_first")
#Expose
private String appearanceFirst;
#SerializedName("appearance_latest")
#Expose
private String appearanceLatest;
public String getScreenName() {
return screenName;
}
public void setScreenName(String screenName) {
this.screenName = screenName;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getProfileImageUrlHttps() {
return profileImageUrlHttps;
}
public void setProfileImageUrlHttps(String profileImageUrlHttps) {
this.profileImageUrlHttps = profileImageUrlHttps;
}
public String getAppearanceFirst() {
return appearanceFirst;
}
public void setAppearanceFirst(String appearanceFirst) {
this.appearanceFirst = appearanceFirst;
}
public String getAppearanceLatest() {
return appearanceLatest;
}
public void setAppearanceLatest(String appearanceLatest) {
this.appearanceLatest = appearanceLatest;
}
}
Aggregations.class
public class Aggregations {
}
And finally, this is the code I use to read the JSON and store as JSON objects,
SharedPreferences Tempx = getSharedPreferences("ActivitySession", Context.MODE_PRIVATE);
SharedPreferences.Editor edx = Tempx.edit();
edx.putString("GSON_FEED", response.toString());
edx.apply();
Gson gson = new Gson();
JsonParser parser = new JsonParser();
try{
JsonArray jArray = parser.parse(Tempx.getString("GSON_FEED","")).getAsJsonArray();
for(JsonElement obj : jArray )
{
MainPojo cse = gson.fromJson( obj , MainPojo.class);
TweetList.add(cse);
}
}catch(Throwable e) {
JsonElement obj = parser.parse(Tempx.getString("GSON_FEED","")).getAsJsonObject();
MainPojo cse = gson.fromJson( obj , MainPojo.class);
TweetList.add(cse);
}
Though I am able to log the JSON as String, I don't know if I am storing it the wrong way, any help will be much appreciated, Thanks!
You could define a custom deserializer and register a type adapter with GSON. Also
why are you using this:
JsonArray jArray = parser.parse(Tempx.getString("GSON_FEED","")).getAsJsonArray();
.. when you intend to use GSON for deserialization? You could just do it in your deserializer.
https://sites.google.com/site/gson/gson-user-guide#TOC-Custom-Serialization-and-Deserialization
EG:
public class FooDeserializer implements JsonDeserializer<Foos>
{
#Override public Foos deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException
{
JsonObject jsonObject = json.getAsJsonObject();
JsonArray statusArray = jsonObject.get("statuses").getAsJsonArray();
Foos result = new Foos();
ArrayList fooArray = new ArrayList<>;
for (JsonElement e : statusArray) {
fooArray.add(new Foo());
}
result.setFoos(fooArray);
return result;
}
}

JSON mapping to Java returning null value

I'm trying to map JSON to Java using gson.I was succesful in writing the logic but unsuccesful in getting the output.Below posted are my JSON and Java files.Any help would be highly appreciated.
This is the output i'm getting
value:null
Below posted is the code for .json files
{
"catitem": {
"id": "1.196289",
"src": "http://feeds.reuters.com/~r/reuters/MostRead/~3/PV-SzW7Pve0/story06.htm",
"orig_item_date": "Tuesday 16 June 2015 07:01:02 PM UTC",
"cat_id": "1",
"heding": "Putin says Russia beefing up nuclear arsenal",
"summary": "KUvdfbefb bngfb",
"body": {
"bpart": [
"KUBINKA,dvdvdvdvgbtgfdnhfbnrtdfbcv dbnfg"
]
}
}
}
Below posted is my .java file
public class offc {
public static void main(String[] args) {
JsonReader jr = null;
try {
jr = new JsonReader(new InputStreamReader(new FileInputStream(
"C:\\Users\\rishii\\IdeaProjects\\rishi\\src\\file3.json")));
} catch (Exception ex) {
ex.printStackTrace();
}
Doll s = new Doll();
Gson g = new Gson();
Doll sr1 = g.fromJson(jr, Doll.class);
System.out.println(sr1);
}
}
Below posted is the code for Doll.java
class Doll {
private catitem ct;
public void setCt(catitem ct) {
this.ct = ct;
}
public catitem getCt() {
return ct;
}
#Override
public String toString()
{
return "value:" + ct;
}
class catitem {
private String id;
private String src;
private String orig_item_date;
private String cat_id;
private String heding;
private String summary;
private body ber;
catitem(String id, String src, String orig_item_date, String cat_id, String heding,
String summary) {
this.id = id;
this.src = src;
this.orig_item_date = orig_item_date;
this.cat_id = cat_id;
this.heding = heding;
this.summary = summary;
}
public void setId(String id) {
this.id = id;
}
public String getId() {
return id;
}
public void setSrc(String src) {
this.src = src;
}
public String getSrc() {
return src;
}
public void setOrig_item_date(String Orig_item_date) {
this.orig_item_date = Orig_item_date;
}
public String getOrig_item_date() {
return getOrig_item_date();
}
public void setCat_id(String cat_id) {
this.cat_id = cat_id;
}
public String getCat_id() {
return cat_id;
}
public void setHeding(String heding) {
this.heding = heding;
}
public String getHeding() {
return heding;
}
public void setSummary(String summary) {
this.summary = summary;
}
public String getSummary() {
return summary;
}
public void setBer(body ber) {
this.ber = ber;
}
public body getBer() {
return ber;
}
#Override
public String toString() {
return "id:" + id + "cat_id" + cat_id + "summary" + summary + "orig_date"
+ orig_item_date + "heding" + heding;
}
}
class body {
private String bpart;
public void setBpart(String r) {
this.bpart = r;
}
public String getBpart() {
return bpart;
}
#Override
public String toString() {
return "hiii";
}
}
}
The issue is in class Doll, You have a field ct but in json catitem. Rename the field ct to catitem or if you are using Gson use #SerializedName("catitem") on filed ct and it will work.

Using GSON giving error expected BEGIN_ARRAY but was STRING

An example JSON object is shown below:
[{"Title":"John Doe","Address":{"AddressLines":["The Place","123 New Place","London","England"],"Postcode":"NW7 XXY"},"Telephone":"0012345","Email":"","Latitude":51.5024472101345,"Longitude":-0.557585646554,"Easting":500623,"Northing":179647}]
Suppose the above object is accessed via the link www.domain.com and I have the following class to represent the data
public class LocationData extends Data{
private Address Address;
private String Telephone;
private String Email;
private String Latitude;
private String Longitude;
private String Easting;
private String Northing;
public Address getAddress() {
return Address;
}
public void setAddress(Address address) {
Address = address;
}
public String getTelephone() {
return Telephone;
}
public void setTelephone(String telephone) {
Telephone = telephone;
}
public String getEmail() {
return Email;
}
public void setEmail(String email) {
Email = email;
}
public String getLatitude() {
return Latitude;
}
public void setLatitude(String latitude) {
Latitude = latitude;
}
public String getLongitude() {
return Longitude;
}
public void setLongitude(String longitude) {
Longitude = longitude;
}
public String getEasting() {
return Easting;
}
public void setEasting(String easting) {
Easting = easting;
}
public String getNorthing() {
return Northing;
}
public void setNorthing(String northing) {
Northing = northing;
}
}
And the address class is as follows:
public class Address {
public String[] AddressLines;
public String Postcode;
public String getPostcode() {
return Postcode;
}
public void setPostcode(String postcode) {
Postcode = postcode;
}
public String[] getAddressLines() {
return AddressLines;
}
public void setAddressLines(String addressLines[]) {
AddressLines = addressLines;
}
}
When I try to run
LocationData[] data = gson.fromJson(this.locationServiceUrl, LocationData[].class);
return data;
I get the following error:
Expected BEGIN_ARRAY but was string at the above mentioned line of code. I am not sure if there is something wrong in the manner in which I have set up my classes. Note: I am using an array (LocationData[] data) because the service returns multiple locations although I have just included one in the example shown above. Any help as to why this is happening is much appreciated. I have looked at some of the similar errors on here but none of the fixes provided seem to work for me.
{
"finally":[
{
"Title":"John Doe",
"Address": {
"AddressLines":[
"The Place",
"123 New Place",
"London",
"England"
],
"Postcode":"NW7XXY"
},
"Telephone":"0012345",
"Email":"",
"Latitude":51.5024472101345,
"Longitude":-0.557585646554,
"Easting":500623,
"Northing":179647
}
]
}
and code to parse this JSON is :
public class mainData {
public List<LocationData> finally;
public String[] getLocationData() {
return AddressLines;
}
public void setLocationData(List<LocationData> finally) {
this.finally = finally;
}
}
it is because your string starting with [ when you parsing this type of Json with Gson then you need to prefix a label to it just i like did ( {"finally": your data }).
Actually Gson trying to map the label and its value but in your case your [ doesnt contain Label by which Gson can map.

Categories