how to access to json with java - java

I have in a rest response this json:
{
"TRANS": {
"HPAY": [
{
"ID": "1234",
"DATE": "10/09/2011 18:09:27",
"REC": "wallet Ricaricato",
"COM": "Tasso Commissione",
"MSG": "Commento White Brand",
"STATUS": "3",
"EXTRA": {
"IS3DS": "0",
"CTRY": "FRA",
"AUTH": "455622"
},
"INT_MSG": "05-00-05 ERR_PSP_REFUSED",
"MLABEL": "IBAN",
"TYPE": "1"
}
]
}
}
I have made pojo class to map this json in java.
public class Trans {
private List<Hpay> hpay;
public Trans(){
}
//getter and setter
}
public class Hpay {
private String id;
private String date;
private String com;
private String msg;
private String status;
private List<Extra> extra;
private String int_msg;
private String mlabel;
private String type;
public Hpay(){
}
//getter and setter
}
I try to map the object with Gson library.
Gson gson=new Gson();
Trans transaction=gson.fromJson(response.toString(), Trans.class);
If i call hpay method on transaction i have null..i don't know why...

I have deleted previous answer and add new one as par your requirement
JSON String :
{
"TRANS": {
"HPAY": [{
"ID": "1234",
"DATE": "10/09/2011 18:09:27",
"REC": "wallet Ricaricato",
"COM": "Tasso Commissione",
"MSG": "Commento White Brand",
"STATUS": "3",
"EXTRA": {
"IS3DS": "0",
"CTRY": "FRA",
"AUTH": "455622"
},
"INT_MSG": "05-00-05 ERR_PSP_REFUSED",
"MLABEL": "IBAN",
"TYPE": "1"
}
]
}
}
Java Objects : (Here Extra is not list)
public class MyObject {
#SerializedName("TRANS")
#Expose
private Trans trans;
public Trans getTRANS() {return trans;}
public void setTRANS(Trans trans) {this.trans = trans;}
}
public class Trans {
#SerializedName("HPAY")
#Expose
private List<HPay> hPay;
public List<HPay> getHPAY() {return hPay;}
public void setHPAY(List<HPay> hPay) {this.hPay = hPay;}
}
public class HPay {
#SerializedName("ID")
#Expose
private String id;
#SerializedName("DATE")
#Expose
private String date;
#SerializedName("REC")
#Expose
private String rec;
#SerializedName("COM")
#Expose
private String com;
#SerializedName("MSG")
#Expose
private String msg;
#SerializedName("STATUS")
#Expose
private String status;
#SerializedName("EXTRA")
#Expose
private Extra extra;
#SerializedName("INT_MSG")
#Expose
private String intMsg;
#SerializedName("MLABEL")
#Expose
private String mLabel;
#SerializedName("TYPE")
#Expose
private String type;
public String getID() {return id;}
public void setID(String id) {this.id = id;}
public String getDATE() {return date;}
public void setDATE(String date) {this.date = date;}
public String getREC() {return rec;}
public void setREC(String rec) {this.rec = rec;}
public String getCOM() {return com;}
public void setCOM(String com) {this.com = com;}
public String getMSG() {return msg;}
public void setMSG(String msg) {this.msg = msg;}
public String getSTATUS() {return status;}
public void setSTATUS(String status) {this.status = status;}
public Extra getEXTRA() {return extra;}
public void setEXTRA(Extra extra) {this.extra = extra;}
public String getINTMSG() {return intMsg;}
public void setINTMSG(String intMsg) {this.intMsg = intMsg;}
public String getMLABEL() {return mLabel;}
public void setMLABEL(String mLabel) {this.mLabel = mLabel;}
public String getTYPE() {return type;}
public void setTYPE(String type) {this.type = type;}
}
public class Extra {
#SerializedName("IS3DS")
#Expose
private String is3ds;
#SerializedName("CTRY")
#Expose
private String ctry;
#SerializedName("AUTH")
#Expose
private String auth;
public String getIS3DS() { return is3ds; }
public void setIS3DS(String is3ds) { this.is3ds = is3ds; }
public String getCTRY() { return ctry; }
public void setCTRY(String ctry) { this.ctry = ctry; }
public String getAUTH() { return auth; }
public void setAUTH(String auth) { this.auth = auth; }
}
Conversion Logic :
import com.google.gson.Gson;
public class NewClass {
public static void main(String[] args) {
Gson g = new Gson();
g.fromJson(json, MyObject.class);
}
static String json = "{ \"TRANS\": { \"HPAY\": [{ \"ID\": \"1234\", \"DATE\": \"10/09/2011 18:09:27\", \"REC\": \"wallet Ricaricato\", \"COM\": \"Tasso Commissione\", \"MSG\": \"Commento White Brand\", \"STATUS\": \"3\", \"EXTRA\": { \"IS3DS\": \"0\", \"CTRY\": \"FRA\", \"AUTH\": \"455622\" }, \"INT_MSG\": \"05-00-05 ERR_PSP_REFUSED\", \"MLABEL\": \"IBAN\", \"TYPE\": \"1\" } ] } }";
}
Here I use Google Gosn lib for conversion.
And need to import bellow classes for annotation
com.google.gson.annotations.Expose;
com.google.gson.annotations.SerializedName;

First parse the json data using json.simple and then set the values using setters
Object obj = parser.parse(new FileReader( "file.json" ));
JSONObject jsonObject = (JSONObject) obj;
JSONArray hpayObj= (JSONArray) jsonObject.get("HPAY");
//get the first element of array
JSONObject details= hpayObj.getJSONArray(0);
String id = (String)details.get("ID");
//set the value of the id field in the setter of class Trans
new Trans().setId(id);
new Trans().setDate((String)details.get("DATE"));
new Trans().setRec((String)details.get("REC"));
and so on..
//get the second array element
JSONObject intMsgObj= hpayObj.getJSONArray(1);
new Trans().setIntmsg((String)details.get("INT_MSG"));
//get the third array element
JSONObject mlabelObj= hpayObj.getJSONArray(2);
new Trans().setMlabel((String)details.get("MLABEL"));
JSONObject typeObj= hpayObj.getJSONArray(3);
new Trans().setType((String)details.get("TYPE"));
Now you can get the values using your getter methods.

Related

Jackson missing out values

I am trying to map a JSON to a simple Java DTO.
Here is my Java structure:
public class VirtualServerResponse {
private String kind;
private String selfLink;
private List<VirtualServer> items = new ArrayList<VirtualServer>();
//no arg constructor
//getters and setters
#JsonIgnoreProperties(ignoreUnknown = true)
public class VirtualServer {
public String kind;
public String name;
public String partition;
public String fullPath;
public String generation;
public String selfLink;
public String addressStatus;
public String autoLasthop;
public String cmpEnabled;
public String connectionLimit;
public String description;
public String destination;
public String enabled;
public String gtmScore;
public String ipProtocol;
public String mask;
public String mirror;
public String mobileAppTunnel;
public String nat64;
public String pool;
public String rateLimit;
public String rateLimitDstMask;
public String rateLimitMode;
public String rateLimitSrcMask;
public String serviceDownImmediateAction;
public String source;
public String sourcePort;
public String synCookieStatus;
public String translateAddress;
public String translatePort;
public String vlansEnabled;
public String vsIndex;
public PoolDTO assignedPool;
public VirtualServer() {
}
//getters and setters
Here is the JSON that should be mapped:
"kind":"tm:ltm:virtual:virtualcollectionstate",
"selfLink":"https://localhost/mgmt/tm/ltm/virtual?expandSubcollections=true&ver=13.1.1.2",
"items":[
{
"kind":"tm:ltm:virtual:virtualstate",
"name":"some_name_with:80",
"partition":"part",
"fullPath":"/part/name",
"generation":58670,
"selfLink":"https://localhost/mgmt/tm/ltm/virtual/~somelink",
"addressStatus":"yes",
"autoLasthop":"default",
"cmpEnabled":"yes",
"connectionLimit":0,
"description":"description",
"destination":"/part/1.1.1.1:80",
"enabled":true,
"gtmScore":0,
"ipProtocol":"tcp",
"mask":"255.255.255.255",
"mirror":"disabled",
"mobileAppTunnel":"disabled",
"nat64":"disabled",
"pool":"/pool",
"poolReference":{
"link":"https://localhost/mgmt/tm/ltm/pool/link"
},
"rateLimit":"disabled",
"rateLimitDstMask":0,
"rateLimitMode":"object",
"rateLimitSrcMask":0,
"serviceDownImmediateAction":"none",
"source":"0.0.0.0/0",
"sourceAddressTranslation":{
"type":"automap"
},
"sourcePort":"preserve",
"synCookieStatus":"not-activated",
"translateAddress":"enabled",
"translatePort":"enabled",
"vlansEnabled":true,
"vsIndex":137,
"vlans":[
"/LAN"
],
"vlansReference":[
{
"link":"https://localhost/mgmt/tm/net/vlan/~LAN?ver=13.1.1.2"
}
],
"policiesReference":{
"link":"https://localhost/mgmt/tm/ltm/virtual/policie",
"isSubcollection":true
},
"profilesReference":{
"link":"https://localhost/mgmt/tm/ltm/virtual/~name",
"isSubcollection":true,
"items":[
{
"kind":"tm:ltm:virtual:profiles:profilesstate",
"name":"stats",
"partition":"part",
"fullPath":"/part/stats",
"generation":3,
"selfLink":"https://localhost/mgmt/tm/ltm/virtual/~name",
"context":"all",
"nameReference":{
"link":"https://localhost/mgmt/tm/ltm/profile/statistics/~part~stats?ver=13.1.1.2"
}
},
{
"kind":"tm:ltm:virtual:profiles:profilesstate",
"name":"tcp",
"partition":"part",
"fullPath":"/part/tcp",
"generation":58670,
"selfLink":"https://localhost/mgmt/tm/ltm/virtual/~name",
"context":"all",
"nameReference":{
"link":"https://localhost/mgmt/tm/ltm/profile/tcp/~part~tcp?ver=13.1.1.2"
}
}
]
}
}, ... next item
The JSON is mapped by the whole JSON in one line:
while ((line = br.readLine()) != null) {
this.jsonResponse = m.readValue(line, VirtualServerResponse.class);
}
I do not need all the subitems in a item, so I used JsonIgnoreUnknown to let them off. However, there are only a few properties, that are mapped:
kind, name, partition, fullPath, generation, selfLink and description.
All others are null. Can someone help me?
It seems that there are properties at different levels.
You have mapped an object with all properties directly under the root, so all other nested properties are not visible.
If the json is something like:
{
"kind":"tm:ltm:virtual:virtualcollectionstate",
"selfLink":"https://localhost/mgmt/tm/ltm/virtual?expandSubcollections=true&ver=13.1.1.2",
"items":[
{
"kind":"tm:ltm:virtual:virtualstate",
"name":"some_name_with:80",
"partition":"part",
"fullPath":"/part/name",
...
}
]
}
You need to map it to an object similar to:
public class VirtualServer {
private String kind;
private String selfLink;
private List<VirtualServer.Item> items;
...
public static class Item {
private String kind;
private String name;
private String partition;
private String fullPath;
...
}
}

Parsing array of object using Gson

My Rest service produces response as below
{
"feeds": [
{
"id": 672,
"imagePath": "http://pixyfi.com/uploads/image1.jpg",
"description": "Off White Cotton Net^The Dress Is Made From Cotton Net. It Is Stretchable And The Material Is Really Good. It Is A Bodycon Dress.",
"uploader": {
"id": 459,
},
"rejected": false,
"moderator": {
"id": 95,
},
"moderatedOn": "2016-12-19"
"imagePaths": [
"uploads/image1.jpg"
]
},
{
"id": 672,
"imagePath": "http://pixyfi.com/uploads/mage2.jpg",
"description": "Off White Cotton Net^The Dress Is Made From Cotton Net. It Is Stretchable And The Material Is Really Good. It Is A Bodycon Dress.",
"uploader": {
"id": 459,
},
"rejected": false,
"moderator": {
"id": 95,
},
"moderatedOn": "2016-12-19"
"imagePaths": [
"uploads/image2.jpg"
]
}
]
}
How can i parse it with Gson. IN my android client also i have same Feed Class witch which this JSON was generated.
Note: I have used Spring boot for my rest API and this JSON was generated with ResponseEntity.
Firstly, make sure that you have got valid JSON. The above in your case is not valid.
If a json object contains a single element, then there is no need to place comma after that. (comma after id in moderator and uploader object). You need to remove that.Also you need to place a comma after moderatedOn value.
Now after you got valid one, you have a feed class. In order to map your json feeds Array onto your List. You need to do the following.
Gson gson = new Gson();
Type feedsType = new TypeToken<ArrayList<Feed>>(){}.getType();
List<Feed> feedList = gson.fromJson(yourJsonResponseArray, feedsType);
Your Classes are must be like these.
Feed Class
public class Feed
{
private String id;
private String imagePath;
private Moderator moderator;
private String description;
private String rejected;
private Uploader uploader;
private String moderatedOn;
private String[] imagePaths;
public String getId ()
{
return id;
}
public void setId (String id)
{
this.id = id;
}
public String getImagePath ()
{
return imagePath;
}
public void setImagePath (String imagePath)
{
this.imagePath = imagePath;
}
public Moderator getModerator ()
{
return moderator;
}
public void setModerator (Moderator moderator)
{
this.moderator = moderator;
}
public String getDescription ()
{
return description;
}
public void setDescription (String description)
{
this.description = description;
}
public String getRejected ()
{
return rejected;
}
public void setRejected (String rejected)
{
this.rejected = rejected;
}
public Uploader getUploader ()
{
return uploader;
}
public void setUploader (Uploader uploader)
{
this.uploader = uploader;
}
public String getModeratedOn ()
{
return moderatedOn;
}
public void setModeratedOn (String moderatedOn)
{
this.moderatedOn = moderatedOn;
}
public String[] getImagePaths ()
{
return imagePaths;
}
public void setImagePaths (String[] imagePaths)
{
this.imagePaths = imagePaths;
}
}
Moderator Class
public class Moderator
{
private String id;
public String getId ()
{
return id;
}
public void setId (String id)
{
this.id = id;
}
}
Uploader Class
public class Uploader
{
private String id;
public String getId ()
{
return id;
}
public void setId (String id)
{
this.id = id;
}
}

JSON to POJO with Integer as Array attribute key Name

I have the following json which has a product array with product_id as each array.Product ids are numbers. When I am looking online for the pojo classes I am getting Class names which starts with digits which is not allowed.
{
"_id:" : "1234AG567",
"products" : {
"1234":{
"product_name" : "xyz",
"product_type" : "abc"
},
"3456":{
"product_name" : "zzz",
"product_type" : "def"
}
}
}
Below are the Pojo classes I am getting
public class MyPojo
{
private Products products;
public Products getProducts ()
{
return products;
}
public void setProducts (Products products)
{
this.products = products;
}
#Override
public String toString()
{
return "ClassPojo [products = "+products+"]";
}
}
public class Products
{
private 1234 1234;
private 3456 3456;
public 1234 get1234 ()
{
return 1234;
}
public void set1234 (1234 1234)
{
this.1234 = 1234;
}
public 3456 get3456 ()
{
return 3456;
}
public void set3456 (3456 3456)
{
this.3456 = 3456;
}
#Override
public String toString()
{
return "ClassPojo [1234 = "+1234+", 3456 = "+3456+"]";
}
}
public class 3456
{
private String product_name;
private String product_type;
public String getProduct_name ()
{
return product_name;
}
public void setProduct_name (String product_name)
{
this.product_name = product_name;
}
public String getProduct_type ()
{
return product_type;
}
public void setProduct_type (String product_type)
{
this.product_type = product_type;
}
#Override
public String toString()
{
return "ClassPojo [product_name = "+product_name+", product_type = "+product_type+"]";
}
}
public class 1234
{
private String product_name;
private String product_type;
public String getProduct_name ()
{
return product_name;
}
public void setProduct_name (String product_name)
{
this.product_name = product_name;
}
public String getProduct_type ()
{
return product_type;
}
public void setProduct_type (String product_type)
{
this.product_type = product_type;
}
#Override
public String toString()
{
return "ClassPojo [product_name = "+product_name+", product_type = "+product_type+"]";
}
}
I have used the http://pojo.sodhanalibrary.com/ to convert
Any help how to create pojo for this JSON is welcome. Thanks in advance.
You can use Map to store the products and wrap it in another class to store the whole json. E.g. Product class would look like this:
class Product {
#JsonProperty("product_name")
private String productName;
#JsonProperty("product_type")
private String productType;
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getProductType() {
return productType;
}
public void setProductType(String productType) {
this.productType = productType;
}
}
Wrapper class would look like this:
class ProductList{
#JsonProperty("_id")
private String id;
private Map<String, Product> products;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Map<String, Product> getProducts() {
return products;
}
public void setProducts(Map<String, Product> products) {
this.products = products;
}
}
Here's is the deserialization example with Jackson:
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
ProductList list = mapper.readValue("{\"_id\" : \"1234AG567\",\"products\" : {\"1234\":{\"product_name\" : \"xyz\",\"product_type\" : \"abc\"},\"3456\":{\"product_name\" : \"zzz\",\"product_type\" : \"def\"}}}", ProductList.class);
System.out.println(list.getId());
System.out.println(list.getProducts());
}
Please note that your json has a typo in it. Id field should be _id and not _id: (if that is the actual field name then you can change JsonProperty annotation to _id:.
Here is documentation for Jackson.
The JSON is valid, but you WILL NOT be able to create POJOs to represent that. Like you have already seen, you cannot create classes that begin with numbers, and you don't want to do this anyway as they won't provide any meaning to you.
I'm going to guess that products is an array of Product, and that number is an ID or something. The JSON should look something like this:
{
"products": [
{
"id": "1234",
"product_name": "xyz",
"product_type": "abc"
},
{
"id": "3456",
"product_name": "zzz",
"product_type": "def"
}]
}
Which would deserialize into a class that contains
private List<Product> products;
assuming that that the Product class looks like
class Product {
private Integer id;
#JsonProperty(value = "product_name")
private String productName;
#JsonProperty(value = "product_type")
private String productType;
}

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

GSON parsing in Java with unknown number of objects

I'm new to GSON and have been having trouble parsing the JSON below. The parsing works fine until it gets to the list of bills (staring at "0":). At that point I get a null reference in the resulting gson.fromJson object. If those bills were specified in a JSON array I think it would be easy, but they're not and I can't change that. What is the best way to handle this situation?
{
"status":"OK",
"masterlist":{
"session":{
"session_id":1007,
"session_name":"97th Legislature"
},
"0":{
"bill_id":446875,
"number":"HB4001"
},
"1":{
"bill_id":446858,
"number":"HB4002"
},
"2":{
"bill_id":446842,
"number":"HB4003"
},...
This is the code in my main method:
InputStream source = retrieveStream(url);
Gson gson = new Gson();
Reader reader = new InputStreamReader(source);
ResponseData response = gson.fromJson(reader, ResponseData.class);
And this is the ResponseData class:
public class ResponseData {
private String status;
private MasterList masterlist;
public static class MasterList{
private Session session;
private Bill bill; //Also tried: Map<String, String> bill;
}
public static class Session{
private String session_id;
private String session_name;
}
public static class Bill{
private String bill_id;
private String number;
}
}
You can map the object as below:
declare an object to map with json string
public class ResponseData {
private String status;
private Map<String, MasterList> masterlist;
public Map<String, MasterList> getMasterlist() {
return masterlist;
}
public void setMasterlist(Map<String, MasterList> masterlist) {
this.masterlist = masterlist;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public static class MasterList {
private String session_id;
private String session_name;
private String bill_id;
private String number;
public String getSession_id() {
return session_id;
}
public void setSession_id(String session_id) {
this.session_id = session_id;
}
public String getSession_name() {
return session_name;
}
public void setSession_name(String session_name) {
this.session_name = session_name;
}
public String getBill_id() {
return bill_id;
}
public void setBill_id(String bill_id) {
this.bill_id = bill_id;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
}
}
And use it as below:
String data = "{\"status\":\"OK\",\"masterlist\":{ \"session\":{ \"session_id\":1007, \"session_name\":\"97th Legislature\" }, \"0\":{ \"bill_id\":446875, \"number\":\"HB4001\" }, \"1\":{ \"bill_id\":446858, \"number\":\"HB4002\" }, \"2\":{ \"bill_id\":446842, \"number\":\"HB4003\" }}}";
Gson gson = new Gson();
ResponseData response = gson.fromJson(data, ResponseData.class);
for (Iterator<Entry<String, MasterList>> it = response.getMasterlist().entrySet().iterator(); it.hasNext(); ) {
Map.Entry<String, MasterList> entry = it.next();
System.out.println(entry.getKey());
System.out.println(entry.getValue().getSession_id());
}

Categories