gson.JsonSyntaxException: java.lang.IllegalStateException: - java

I am new to gson and getting this error.
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2527 path $.data.batting[0].scores[1].dismissal-by
it is because of the different json reply given by the API.
this is the json reply:
"batting": [
{
"scores": [
{
"dismissal-by": {
"name": "CE Rudd",
"pid": "646213"
},
"dismissal": "stumped",
"SR": 126,
"6s": 0,
"4s": 5,
"B": 34,
"R": 43,
"dismissal-info": "st Rudd b Kerr",
"batsman": "NE Bolton",
"pid": "267611"
},
{
"dismissal-by": [
{
"name": "M du Preez",
"pid": "54646"
}
],
"dismissal": "runout",
"SR": 112,
"6s": 0,
"4s": 4,
"B": 25,
"R": 28,
"dismissal-info": "run out (du Preez)",
"batsman": "GEB Boyce",
"pid": "874261"
},
{
"dismissal-by": {
"name": "LK Bell",
"pid": "878025"
},
"dismissal": "catch",
"SR": 100,
"6s": 0,
"4s": 2,
"B": 27,
"R": 27,
"dismissal-info": "c Bell b Scholfield",
"batsman": "AE Satterthwaite",
"pid": "233007"
},
{
"dismissal": "not out",
"SR": 220,
"6s": 2,
"4s": 5,
"B": 20,
"R": 44,
"dismissal-info": "not out",
"batsman": "H Kaur",
"pid": "372317"
},
{
"dismissal": "not out",
"SR": 100,
"6s": 0,
"4s": 1,
"B": 14,
"R": 14,
"dismissal-info": "not out",
"batsman": "E Threlkeld ",
"pid": "878035"
},
{
"SR": "",
"6s": "",
"4s": "",
"B": "",
"R": "",
"dismissal-info": "",
"detail": "6 (b 1, w 5)",
"batsman": "Extras",
"pid": 0
}
],
"title": "Lancashire Thunder Innings"
},
getting the error at the 2nd dismissal-by object.
the 1st dismissal-by starts with an object and the second dismissal-by object by an array.
this is the java class for the scores array
public class Score__ implements Serializable {
#SerializedName("dismissal-by")
#Expose
private DismissalBy dismissalBy;
#SerializedName("dismissal")
#Expose
private String dismissal;
#SerializedName("SR")
#Expose
private String sR;
#SerializedName("6s")
#Expose
private String _6s;
#SerializedName("4s")
#Expose
private String _4s;
#SerializedName("B")
#Expose
private String b;
#SerializedName("R")
#Expose
private String r;
#SerializedName("dismissal-info")
#Expose
private String dismissalInfo;
#SerializedName("batsman")
#Expose
private String batsman;
#SerializedName("pid")
#Expose
private Integer pid;
#SerializedName("detail")
#Expose
private String detail;
public DismissalBy getDismissalBy() {
return dismissalBy;
}
public void setDismissalBy(DismissalBy dismissalBy) {
this.dismissalBy = dismissalBy;
}
public String getDismissal() {
return dismissal;
}
public void setDismissal(String dismissal) {
this.dismissal = dismissal;
}
public String getSR() {
return sR;
}
public void setSR(String sR) {
this.sR = sR;
}
public String get6s() {
return _6s;
}
public void set6s(String _6s) {
this._6s = _6s;
}
public String get4s() {
return _4s;
}
public void set4s(String _4s) {
this._4s = _4s;
}
public String getB() {
return b;
}
public void setB(String b) {
this.b = b;
}
public String getR() {
return r;
}
public void setR(String r) {
this.r = r;
}
public String getDismissalInfo() {
return dismissalInfo;
}
public void setDismissalInfo(String dismissalInfo) {
this.dismissalInfo = dismissalInfo;
}
public String getBatsman() {
return batsman;
}
public void setBatsman(String batsman) {
this.batsman = batsman;
}
public Integer getPid() {
return pid;
}
public void setPid(Integer pid) {
this.pid = pid;
}
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
}
the dismissal-by java class
public class DismissalBy implements Serializable {
#SerializedName("name")
#Expose
private String name;
#SerializedName("pid")
#Expose
private String pid;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPid() {
return pid;
}
public void setPid(String pid) {
this.pid = pid;
}
}
how do i fix this problem ?
any help will be appreciated

in your JSON object, there is a
"dismissal-by": {
"name": "LK Bell",
"pid": "878025"
},
you cannot use it like this since you declare it as an array it should stay at the same type there for you need to change it to something like
"dismissal-by"":[
{
"name": "LK Bell",
"pid": "878025"
}
]
,
to fix this issue you need to parse all JSON manually like
Json json = new Json(string);
try{
json.getJsonArray("dismissal-by");
}catch(IllegalStateException e)
{
json.getObject("dismissal-by");
}

that JSON is invalid... therefore the com.google.gson.JsonSyntaxException.
it needs to start with a { and after "title": "Lancashire Thunder Innings", there is a }] missing.
there you can check for yourself: https://jsonlint.com

The dismissal-by you are getting is Some time in array format (start with [ and end with ]) while some time it is Json object {} it will be better to resolve it from API developer. Or you can declare it as String and do parsing later where required.
public class Score__ implements Serializable {
#SerializedName("dismissal-by")
#Expose
private String dismissalBy;}

Related

Jackson obectMapperwriteValue() not working as expected

I deserialize the data.json file to Customer.java. And tried to serialize Customer.java to shopping.json. But it is showing two list objects (list and food) in the serialized json data. There should be only one list (i.e., food). What went wrong? Please see the code below:
ShoppingList.java
private String name;
private int amount;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
#Override
public String toString() {
return "ShoppingList [name=" + name + ", amount=" + amount + "]";
}
Customer.java
private String date;
private String name;
private String store;
#JsonProperty("food")
private List<ShoppingList> food;
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStore() {
return store;
}
public void setStore(String store) {
this.store = store;
}
public List<ShoppingList> getList() {
return food;
}
public void setList(List<ShoppingList> list) {
this.food = list;
}
#Override
public String toString() {
return "Customer [date=" + date + ", name=" + name + ", store=" + store + ", food=" + food + "]";
}
Test.java
public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
File file = new File("data.json");
ObjectMapper mapper = new ObjectMapper();
Customer m = mapper.readValue(file, Customer.class);
System.out.println(m.toString());
System.out.println(m.getList().toString());
mapper.writeValue(new File("shopping.json"), m);
}
data.json
{
"date": "2016-07-14",
"name": "Candice",
"store": "aStore",
"food": [
{
"name": "eggs",
"amount": 6
},
{
"name": "Chicken",
"amount": 1
},
{
"name": "Bananas",
"amount": 5
},
{
"name": "Pasta",
"amount": 1
}
]
}
shopping.json
{
"date": "2016-07-14",
"name": "Candice",
"store": "aStore",
"list": [ //This list is generated extra.
{
"name": "eggs",
"amount": 6
},
{
"name": "Chicken",
"amount": 1
},
{
"name": "Bananas",
"amount": 5
},
{
"name": "Pasta",
"amount": 1
}
],
"food": [
{
"name": "eggs",
"amount": 6
},
{
"name": "Chicken",
"amount": 1
},
{
"name": "Bananas",
"amount": 5
},
{
"name": "Pasta",
"amount": 1
}
]
}
I tried in different ways but no luck.
Thanks in advance.
This might be caused for your naming. Rename you getList method and setList method to getFood and setFood and try again.

String to Array using Json

I have an Array of Json elements as a String, my problem is how to convert them into and Object Array using Gson.
I found some methods on this site but non of them seem to work for my String.
["2": {"id": 2, "name": "Cannonball", "sp": 5, "overall_average": 194, "buy_average": 193, "members": true, "sell_average": 193},
"6": {"id": 6, "name": "Cannon base", "sp": 187500, "overall_average": 188110, "buy_average": 184547, "members": true, "sell_average": 185735},
"12289": {"id": 12289, "name": "Mithril platelegs (t)", "sp": 2600, "overall_average": 0, "buy_average": 3000, "members": false, "sell_average": 3000},
"8": {"id": 8, "name": "Cannon stand", "sp": 187500, "overall_average": 198445, "buy_average": 189001, "members": true, "sell_average": 190889},
"10": {"id": 10, "name": "Cannon barrels", "sp": 187500, "overall_average": 194418, "buy_average": 185164, "members": true, "sell_average": 185935},
"12": {"id": 12, "name": "Cannon furnace", "sp": 187500, "overall_average": 188000, "buy_average": 186524, "members": true, "sell_average": 186637},
"4099": {"id": 4099, "name": "Mystic hat (dark)", "sp": 15000, "overall_average": 9758, "buy_average": 9229, "members": true, "sell_average": 9528}]
I need to convert the data to this java object.
public class OSBuddyItem {
private final int id;
private final String name;
private final int sellPrice;
private final int buyPrice;
private final int averagePrice;
private final int storePrice;
private final boolean members;
public OSBuddyItem(int id, String name, int sellPrice, int buyPrice, int averagePrice, int storePrice, boolean members){
this.id = id;
this.name = name;
this.sellPrice = sellPrice;
this.buyPrice = buyPrice;
this.averagePrice = averagePrice;
this.storePrice = storePrice;
this.members = members;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public int getSellPrice() {
return sellPrice;
}
public int getBuyPrice() {
return buyPrice;
}
public int getAveragePrice() {
return averagePrice;
}
public int getStorePrice() {
return storePrice;
}
public boolean isMembers() {
return members;
}
}
This is what I tried:
Gson gson = new Gson();
JsonParser parser = new JsonParser();
JsonElement tradeElement = parser.parse(data);
JsonArray itemElements = tradeElement.getAsJsonArray();
OSBuddyItem[] items = gson.fromJson(itemElements,OSBuddyItem[].class);
for(OSBuddyItem item : items){
System.out.println(item.getName());
}
Can someone please tell me how to convert the String using Gson?
Your JSON String is not valid.You can validate your JSON String from [http://jsoneditoronline.org/][1]
Suppose if JSON String is in form :-
[{"1": {"id": 2, "name": "Cannonball", "sp": 5, "overall_average": 194, "buy_average": 193, "members": true, "sell_average": 193}}]
Suppose Model Name is Example.Then Model of Json will be :-
package com.example;
import com.google.gson.annotations.SerializedName;
public class Example {
#SerializedName("id")
private Integer id;
#SerializedName("name")
private String name;
#SerializedName("sp")
private Integer sp;
#SerializedName("overall_average")
private Integer overallAverage;
#SerializedName("buy_average")
private Integer buyAverage;
#SerializedName("members")
private Boolean members;
#SerializedName("sell_average")
private Integer sellAverage;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getSp() {
return sp;
}
public void setSp(Integer sp) {
this.sp = sp;
}
public Integer getOverallAverage() {
return overallAverage;
}
public void setOverallAverage(Integer overallAverage) {
this.overallAverage = overallAverage;
}
public Integer getBuyAverage() {
return buyAverage;
}
public void setBuyAverage(Integer buyAverage) {
this.buyAverage = buyAverage;
}
public Boolean getMembers() {
return members;
}
public void setMembers(Boolean members) {
this.members = members;
}
public Integer getSellAverage() {
return sellAverage;
}
public void setSellAverage(Integer sellAverage) {
this.sellAverage = sellAverage;
}
}
And using GSON ,you can convert like below.
[Note :TypeToken class is used to load JSON String into a custom Object]
List<Example> myList = new Gson().fromJson(br, new TypeToken<List<JsonLog>>(){}.getType());

GSON NumberFormatException when lists are involved

I'm trying to parse the JSON from an API request into POJO objects.
The JSON data that I receive:
{
"friends": {
"user": [
{
"name": "Tomstyan",
"image": [
{
"#text": "https://lastfm-img2.akamaized.net/i/u/34s/24514aeefa73fab11c176cbf38a331ae.png",
"size": "small"
},
{
"#text": "https://lastfm-img2.akamaized.net/i/u/64s/24514aeefa73fab11c176cbf38a331ae.png",
"size": "medium"
},
{
"#text": "https://lastfm-img2.akamaized.net/i/u/174s/24514aeefa73fab11c176cbf38a331ae.png",
"size": "large"
},
{
"#text": "https://lastfm-img2.akamaized.net/i/u/300x300/24514aeefa73fab11c176cbf38a331ae.png",
"size": "extralarge"
}
],
"url": "https://www.last.fm/user/Tomstyan",
"country": "",
"age": "0",
"gender": "n",
"subscriber": "FIXME",
"playcount": "714",
"playlists": "0",
"bootstrap": "0",
"registered": {
"unixtime": "1456094418"
},
"type": "FIXME",
"scrobblesource": "FIXME"
},
{
"name": "Bigham96",
"image": [
{
"#text": "https://lastfm-img2.akamaized.net/i/u/34s/2ca8614f31e70fcabe0678a8a622d48c.png",
"size": "small"
},
{
"#text": "https://lastfm-img2.akamaized.net/i/u/64s/2ca8614f31e70fcabe0678a8a622d48c.png",
"size": "medium"
},
{
"#text": "https://lastfm-img2.akamaized.net/i/u/174s/2ca8614f31e70fcabe0678a8a622d48c.png",
"size": "large"
},
{
"#text": "https://lastfm-img2.akamaized.net/i/u/300x300/2ca8614f31e70fcabe0678a8a622d48c.png",
"size": "extralarge"
}
],
"url": "https://www.last.fm/user/Bigham96",
"country": "",
"age": "0",
"gender": "n",
"subscriber": "FIXME",
"playcount": "16988",
"playlists": "0",
"bootstrap": "0",
"registered": {
"unixtime": "1445348751"
},
"type": "FIXME",
"scrobblesource": "FIXME"
},
{
"name": "UKJonnyMfc",
"realname": "Jonny Dring",
"image": [
{
"#text": "https://lastfm-img2.akamaized.net/i/u/34s/f600685470064369c306879e464cb470.png",
"size": "small"
},
{
"#text": "https://lastfm-img2.akamaized.net/i/u/64s/f600685470064369c306879e464cb470.png",
"size": "medium"
},
{
"#text": "https://lastfm-img2.akamaized.net/i/u/174s/f600685470064369c306879e464cb470.png",
"size": "large"
},
{
"#text": "https://lastfm-img2.akamaized.net/i/u/300x300/f600685470064369c306879e464cb470.png",
"size": "extralarge"
}
],
"url": "https://www.last.fm/user/UKJonnyMfc",
"country": "",
"age": "0",
"gender": "n",
"subscriber": "FIXME",
"playcount": "29056",
"playlists": "0",
"bootstrap": "0",
"registered": {
"#text": "2014-02-11 22:38:27",
"unixtime": "1392158307"
},
"type": "FIXME",
"scrobblesource": "FIXME"
}
],
"#attr": {
"for": "tomgreen32",
"page": "1",
"perPage": "50",
"totalPages": "1",
"total": "3"
}
}
}
And the Objects i have to put these in are as follows:
Friends
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Friends {
#SerializedName("user")
#Expose
private List<User> user = null;
#SerializedName("#attr")
#Expose
private Attr attr;
public List<User> getUser() {
return user;
}
public void setUser(List<User> user) {
this.user = user;
}
public Attr getAttr() {
return attr;
}
public void setAttr(Attr attr) {
this.attr = attr;
}
}
Attr
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Attr {
#SerializedName("for")
#Expose
private String _for;
#SerializedName("page")
#Expose
private String page;
#SerializedName("perPage")
#Expose
private String perPage;
#SerializedName("totalPages")
#Expose
private String totalPages;
#SerializedName("total")
#Expose
private String total;
public String getFor() {
return _for;
}
public void setFor(String _for) {
this._for = _for;
}
public String getPage() {
return page;
}
public void setPage(String page) {
this.page = page;
}
public String getPerPage() {
return perPage;
}
public void setPerPage(String perPage) {
this.perPage = perPage;
}
public String getTotalPages() {
return totalPages;
}
public void setTotalPages(String totalPages) {
this.totalPages = totalPages;
}
public String getTotal() {
return total;
}
public void setTotal(String total) {
this.total = total;
}
}
Image
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Image {
#SerializedName("#text")
#Expose
private String text;
#SerializedName("size")
#Expose
private String size;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getSize() {
return size;
}
public void setSize(String size) {
this.size = size;
}
}
Registered
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Registered {
#SerializedName("#text")
#Expose
private String text;
#SerializedName("unixtime")
#Expose
private String unixtime;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getUnixtime() {
return unixtime;
}
public void setUnixtime(String unixtime) {
this.unixtime = unixtime;
}
}
Main
In my main class i have the following code to parse the JSON.
final URL reqURL = new URL("http://ws.audioscrobbler.com/2.0/?method=user.getfriends&" +
"user=" + username +
"&api_key=" + API_KEY +
"&format=json");
final InputStream inputstream = APISend(reqURL);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputstream));
GetFriends getfriends = gson.fromJson(reader, GetFriends.class);
System.out.println(getfriends.getFriends().getUser().get(0).getName());
From what I've read, the list of users might be causing an issue, I've read about TypeToken but i cant figure out how to implement it. This is the first time I've tried to do anything with gson so any help would be appriceted. Thanks.
UPDATE
The error in full
Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.NumberFormatException: For input string: "2014-02-11 22:38:27"
at com.google.gson.internal.bind.TypeAdapters$11.read(TypeAdapters.java:249)
at com.google.gson.internal.bind.TypeAdapters$11.read(TypeAdapters.java:239)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:116)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:216)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:116)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:216)
at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.read(TypeAdapterRuntimeTypeWrapper.java:40)
at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:82)
at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:61)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:116)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:216)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:116)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:216)
at com.google.gson.Gson.fromJson(Gson.java:879)
at com.google.gson.Gson.fromJson(Gson.java:817)
at Main.getUserFriends(Main.java:66)
at Main.main(Main.java:89)
Caused by: java.lang.NumberFormatException: For input string: "2014-02-11 22:38:27"
at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)
at sun.misc.FloatingDecimal.parseDouble(Unknown Source)
at java.lang.Double.parseDouble(Unknown Source)
at com.google.gson.stream.JsonReader.nextInt(JsonReader.java:1198)
at com.google.gson.internal.bind.TypeAdapters$11.read(TypeAdapters.java:247)
... 16 more
UPDATE 2
GetFriends method was created when i used http://www.jsonschema2pojo.org/ to generate the pojo's
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class GetFriends {
#SerializedName("friends")
#Expose
private Friends friends;
public Friends getFriends() {
return friends;
}
public void setFriends(Friends friends) {
this.friends = friends;
}
}

With Gson, how to parse JSON response having complex structure

As you can see the objects matchField and actions are arrays holding objects having different members. Please say what should be my class structure to get this JSON data parsed so that I can get all the data (Please note that the objects in n matchField and actions can have other members- not only the ones in this response). Also is there any other way with GSON(other than using gson.fromJson) to get this done?
{
"node": {
"id": "00:00:00:00:00:00:00:01",
"type": "OF"
},
"flowStatistic": [
{
"flow": {
"match": {
"matchField": [
{
"type": "DL_TYPE",
"value": "2048"
},
{
"mask": "255.255.255.255",
"type": "NW_DST",
"value": "10.0.0.1"
}
]
},
"actions": [
{
"type": "SET_DL_DST",
"address": "7a11761ae595"
},
{
"type": "OUTPUT",
"port": {
"node": {
"id": "00:00:00:00:00:00:00:01",
"type": "OF"
},
"id": "1",
"type": "OF"
}
}
],
"priority": 1,
"idleTimeout": 0,
"hardTimeout": 0,
"id": 0
},
"tableId": 0,
"durationSeconds": 62500,
"durationNanoseconds": 513000000,
"packetCount": 0,
"byteCount": 0
},
{
"flow": {
"match": {
"matchField": [
{
"type": "DL_TYPE",
"value": "2048"
},
{
"mask": "255.255.255.255",
"type": "NW_DST",
"value": "10.0.0.2"
}
]
},
"actions": [
{
"type": "OUTPUT",
"port": {
"node": {
"id": "00:00:00:00:00:00:00:01",
"type": "OF"
},
"id": "2",
"type": "OF"
}
}
],
"priority": 1,
"idleTimeout": 0,
"hardTimeout": 0,
"id": 0
},
"tableId": 0,
"durationSeconds": 62500,
"durationNanoseconds": 508000000,
"packetCount": 0,
"byteCount": 0
},
{
"flow": {
"match": {
"matchField": [
{
"type": "DL_TYPE",
"value": "2048"
},
{
"type": "IN_PORT",
"value": "OF|2#OF|00:00:00:00:00:00:00:01"
}
]
},
"actions": [
{
"type": "SET_NW_TOS",
"tos": 30
}
],
"priority": 500,
"idleTimeout": 0,
"hardTimeout": 0,
"id": 0
},
"tableId": 0,
"durationSeconds": 62252,
"durationNanoseconds": 633000000,
"packetCount": 0,
"byteCount": 0
}
]
}
Following are the POJOs created
public class FlowStatisticsList {
#Expose
#SerializedName("node")
private Node node;
#Expose
#SerializedName("flowStatistic")
private List<FlowStatistic> flowStatistic = new ArrayList<FlowStatistic>();
public Node getNode() {
return node;
}
public void setNode(Node node) {
this.node = node;
}
public List<FlowStatistic> getFlowStatistic() {
return flowStatistic;
}
public void setFlowStatistic(List<FlowStatistic> flowStatistic) {
this.flowStatistic = flowStatistic;
}
}
public class FlowStatistic {
#Expose
#SerializedName("flow")
private Flow flow;
#Expose
#SerializedName("tableId")
private long tableId;
#Expose
#SerializedName("durationSeconds")
private long durationSeconds;
#Expose
#SerializedName("durationNanoseconds")
private long durationNanoseconds;
#Expose
#SerializedName("packetCount")
private long packetCount;
#Expose
#SerializedName("byteCount")
private long byteCount;
public Flow getFlow() {
return flow;
}
public void setFlow(Flow flow) {
this.flow = flow;
}
public long getTableId() {
return tableId;
}
public void setTableId(long tableId) {
this.tableId = tableId;
}
public long getDurationSeconds() {
return durationSeconds;
}
public void setDurationSeconds(long durationSeconds) {
this.durationSeconds = durationSeconds;
}
public long getDurationNanoseconds() {
return durationNanoseconds;
}
public void setDurationNanoseconds(long durationNanoseconds) {
this.durationNanoseconds = durationNanoseconds;
}
public long getPacketCount() {
return packetCount;
}
public void setPacketCount(long packetCount) {
this.packetCount = packetCount;
}
public long getByteCount() {
return byteCount;
}
public void setByteCount(long byteCount) {
this.byteCount = byteCount;
}
}
public class Flow {
#Expose
#SerializedName("match")
private Match match;
#Expose
#SerializedName("actions")
private List<Action> actions = new ArrayList<Action>();
#Expose
#SerializedName("priority")
private long priority;
#Expose
#SerializedName("idleTimeout")
private long idleTimeout;
#Expose
#SerializedName("hardTimeout")
private long hardTimeout;
#Expose
#SerializedName("id")
private long id;
public Match getMatch() {
return match;
}
public void setMatch(Match match) {
this.match = match;
}
public List<Action> getActions() {
return actions;
}
public void setActions(List<Action> actions) {
this.actions = actions;
}
public long getPriority() {
return priority;
}
public void setPriority(long priority) {
this.priority = priority;
}
public long getIdleTimeout() {
return idleTimeout;
}
public void setIdleTimeout(long idleTimeout) {
this.idleTimeout = idleTimeout;
}
public long getHardTimeout() {
return hardTimeout;
}
public void setHardTimeout(long hardTimeout) {
this.hardTimeout = hardTimeout;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
}
public class Match {
#Expose
#SerializedName("matchField")
private List<MatchField> matchField = new ArrayList<MatchField>();
public List<MatchField> getMatchField() {
return matchField;
}
public void setMatchField(List<MatchField> matchField) {
this.matchField = matchField;
}
}
I'm stuck at creating POJOs for Action and MatchField.
The following snippet is used to deserialize the response
gson.fromJson(jsonString, FlowStatisticsList.class)
The following are the POJO classes that you need to create to parse the JSON data into corresponding java object
FlowStatisticsList:
public class FlowStatisticsList {
private Node node;
private List<FlowStatistic> flowStatistic = new ArrayList<FlowStatistic>();
// getters, setters & toString methods
}
Node:
public class Node {
private String id;
private String type;
// getters, setters & toString methods
}
FlowStatistic:
public class FlowStatistic {
private Flow flow;
private long tableId;
private long durationSeconds;
private long durationNanoseconds;
private long packetCount;
private long byteCount;
// getters, setters & toString methods
}
Flow:
public class Flow {
private Match match;
private List<Action> actions = new ArrayList<Action>();
private long priority;
private long idleTimeout;
private long hardTimeout;
private long id;
// getters, setters & toString methods
}
Match:
public class Match {
private List<MatchField> matchField = new ArrayList<MatchField>();
// getters, setters & toString methods
}
MatchField:
public class MatchField {
private String mask;
private String type;
private String value;
// getters, setters & toString methods
}
Action:
public class Action {
private String type;
private String address;
private int tos;
private Port port;
// getters, setters & toString methods
}
Port:
public class Port {
private Node node;
private String type;
private String id;
// getters, setters & toString methods
}
and finally the parsing is as follows:
Gson gson = new GsonBuilder().create();
FlowStatisticsList object = gson.fromJson(jsonData, FlowStatisticsList.class);
System.out.println(object);

gson parsing nested json objects from google matrix api

I want to do something like this posted here, but using this JSON response:
{
"status": "OK",
"origin_addresses": [ "Vancouver, BC, Canada", "Seattle, État de Washington, États-Unis" ],
"destination_addresses": [ "San Francisco, Californie, États-Unis", "Victoria, BC, Canada" ],
"rows": [ {
"elements": [ {
"status": "OK",
"duration": {
"value": 340110,
"text": "3 jours 22 heures"
},
"distance": {
"value": 1734542,
"text": "1 735 km"
}
}, {
"status": "OK",
"duration": {
"value": 24487,
"text": "6 heures 48 minutes"
},
"distance": {
"value": 129324,
"text": "129 km"
}
} ]
}, {
"elements": [ {
"status": "OK",
"duration": {
"value": 288834,
"text": "3 jours 8 heures"
},
"distance": {
"value": 1489604,
"text": "1 490 km"
}
}, {
"status": "OK",
"duration": {
"value": 14388,
"text": "4 heures 0 minutes"
},
"distance": {
"value": 135822,
"text": "136 km"
}
} ]
} ]
}
my classes are:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import com.google.gson.Gson;
import com.google.gson.stream.JsonReader;
class Response {
private String status;
private String[] destination_addresses;
private String[] origin_addresses;
private Elements[] rows;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String[] getDestination_addresses() {
return destination_addresses;
}
public void setDestination_addresses(String[] destination_addresses) {
this.destination_addresses = destination_addresses;
}
public String[] getOrigin_addresses() {
return origin_addresses;
}
public void setOrigin_addresses(String[] origin_addresses) {
this.origin_addresses = origin_addresses;
}
public Elements[] getRows() {
return rows;
}
public void setRows(Elements[] rows) {
this.rows = rows;
}
}
class Distance {
private String text;
private String value;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
class Duration {
private String text;
private String value;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
class Elements {
Duration duration[];
Distance distance[];
String status;
}
public class JSON {
public static void main(String[] args) throws IOException {
JsonReader reader = new JsonReader(new BufferedReader(new FileReader(
"json.json")));
reader.setLenient(true);
Response r = (new Gson().fromJson(reader, Response.class));
StringBuilder sb = new StringBuilder();
for (String s : r.getDestination_addresses()) {
sb.append(s);
}
System.out.println("getDestination_addresses: " + sb.toString());
StringBuilder sb1 = new StringBuilder();
for (String s : r.getOrigin_addresses()) {
sb1.append(s);
}
System.out.println("getOrigin_addresses: " + sb1.toString());
System.out.println("getStatus(): " + r.getStatus());
System.out.println("Rows length " + r.getRows().length);
System.out.println(r.getRows()[0].status); // here i get null
}
}
But it does not work fully, I can get only this fields correctly:
private String status;
private String[] destination_addresses;
private String[] origin_addresses;
the are information is null.
Your declarations are wrong. Change Response into
class Response {
private String status;
private String[] destination_addresses;
private String[] origin_addresses;
private Item[] rows;
...
}
where Item is:
class Item {
private Element[] elements;
...
}
and Element is:
class Element{
Duration duration;
Distance distance;
String status;
...
}
This should solve. Three more tips for you:
We are in full generics era, so avoid Element[] and use List instead (and so on, anycase I kept you "style" in answer)
Use something like this to visualize your JSON, it will help you to understand its structure
Duration and Distance have the same structure, maybe you can save a declaration, Gson does not care about name of classes, it looks at structure of it. From Gson point of view, Duration and Distance are the same: a string plus an integer.

Categories

Resources