gson parsing nested json objects from google matrix api - java

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.

Related

Java JSONObject.getJSONArray always returns null

I want to use the Google Distance Matrix API to get the duration needed to travel between two locations. But when I try to get the duration from the returned data (JSON encoded) the method getJSONArray always returns null.
Here is the data sent by Google:
{
"destination_addresses" : [ "Rome, Metropolitan City of Rome, Italy" ],
"origin_addresses" : [ "Berlin, Germany" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "1,501 km",
"value" : 1501458
},
"duration" : {
"text" : "15 hours 5 mins",
"value" : 54291
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
And here is the method to get the duration:
public static int getDurationFromJSON(String json){
try {
JSONObject jsonObj = new JSONObject(json)
.getJSONArray("rows")
.getJSONObject(0)
.getJSONArray ("elements")
.getJSONObject(0)
.getJSONObject("duration");
return (int)(jsonObj.getInt("value") / 60.0f + 0.5f);
} catch (Exception e) {
e.printStackTrace();
}
return -1;
}
getJSONArray("rows") returns null.
I am not sure why you are getting the null, but this line seems excessive:
(int)(Integer.parseInt(String.valueOf(jsonObj.getInt("value"))) / 60.0f + 0.5f);
JsonObj.getInt("Value) is going to return an int, why are you turning this into a string, only to then parse it back into an Int and then casting that back into an INT again?
This could be simplified into simply like this
return(int)((jsonObj.getInt("value")/60.0f) +0.5f)
As to the null, I would use a debugger and check the JSON being passed in and make sure it is what you think it is.
Also, as other have suggested, using something like restTemplate to auto parse the json into native mapped objects will make your life easier.
Okay, here the solution. Don't trust org.json.* Use Gson:
Json-Data:
{
"destination_addresses" : [ "Rome, Metropolitan City of Rome, Italy" ],
"origin_addresses" : [ "Berlin, Germany" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "1,501 km",
"value" : 1501458
},
"duration" : {
"text" : "15 hours 5 mins",
"value" : 54291
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
Create Object for Result:
public class DirectionMatrixResult {
private String[] destination_addresses;
private String[] origin_addresses;
private DirectionMatrixResultRow[] rows;
public DirectionMatrixResultRow[] getRows() {
return rows;
}
public String[] getDestination_addresses() {
return destination_addresses;
}
public String[] getOrigin_addresses() {
return origin_addresses;
}
public void setDestination_addresses(String[] destination_addresses) {
this.destination_addresses = destination_addresses;
}
public void setOrigin_addresses(String[] origin_addresses) {
this.origin_addresses = origin_addresses;
}
public void setRows(DirectionMatrixResultRow[] rows) {
this.rows = rows;
}
}
public class DirectionMatrixResultRow {
private DirectionMatrixResultElement[] elements;
public DirectionMatrixResultElement[] getElements() {
return elements;
}
public void setElements(DirectionMatrixResultElement[] elements) {
this.elements = elements;
}
}
public class DirectionMatrixResultElement {
private DirectionMatrixResultElementValue distance;
private DirectionMatrixResultElementValue duration;
private String status;
public DirectionMatrixResultElementValue getDistance() {
return distance;
}
public DirectionMatrixResultElementValue getDuration() {
return duration;
}
public String getStatus() {
return status;
}
public void setDistance(DirectionMatrixResultElementValue distance) {
this.distance = distance;
}
public void setDuration(DirectionMatrixResultElementValue duration) {
this.duration = duration;
}
public void setStatus(String status) {
this.status = status;
}
}
public class DirectionMatrixResultElementValue {
private String text;
private long value;
public long getValue() {
return value;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public void setValue(long value) {
this.value = value;
}
}
Then call:
public static int getDurationFromJSON(String json){
try {
Gson gson = new Gson();
DirectionMatrixResult result = gson.fromJson(json, DirectionMatrixResult.class);
return (int)(result.getRows()[0].getElements()[0].getDuration().getValue() / 60.0f + 0.0f);
} catch (Exception e) {
e.printStackTrace();
}
return -1;
}

java.lang.RuntimeException: Unable to invoke no-args constructor for class DBExecuter.Queryjson$valIOConfigclass

I am parsing a json string using fromjson method of gson, when I run the parser as standalone java application, it works but when I run it from an EAR, i'm getting this error:
java.lang.RuntimeException: Unable to invoke no-args constructor for class DBExecuter.Queryjson$valIOConfigclass. Register an InstanceCreator with Gson for this type may fix this problem.
Any help regarding this issue is appreciated
json:
{
"code": "code1",
"query": "text",
"type": "10",
"_condqflg": "1",
"_pkgvarflg": "0",
"_IOSerial": "1|2|5",
"_ioConfig": [{
"_iosl": "1",
"_iokey": "text",
"_iotype": "I",
"_ioflag": "I"
},
{
"_iosl": "2",
"_iokey": "text",
"_iotype": "V",
"_ioflag": "I"
},
{
"_iosl": "3",
"_iokey": "text",
"_iotype": "I",
"_ioflag": "I"
},
{
"_iosl": "4",
"_iokey": "CLIENT_NUM",
"_iotype": "I",
"_ioflag": "1"
}
],
"_valcfg": [{
"_cfgsl": "1",
"_cfgstr": "text",
"_cfgioSl": "4"
},
{
"_cfgsl": "2",
"_cfgstr": "text",
"_cfgioSl": "3|1"
}
]
},
{
"code": "code2",
"query": "text",
"type": "10",
"_condqflg": "1",
"_pkgvarflg": "0",
"_IOSerial": "1|2|5",
"_ioConfig": [{
"_iosl": "1",
"_iokey": "text",
"_iotype": "I",
"_ioflag": "I"
},
{
"_iosl": "2",
"_iokey": "text",
"_iotype": "V",
"_ioflag": "I"
},
{
"_iosl": "3",
"_iokey": "text",
"_iotype": "I",
"_ioflag": "I"
},
{
"_iosl": "4",
"_iokey": "CLIENT_NUM",
"_iotype": "I",
"_ioflag": "1"
}
],
"_valcfg": [{
"_cfgsl": "1",
"_cfgstr": "text",
"_cfgioSl": "4"
},
{
"_cfgsl": "2",
"_cfgstr": "text",
"_cfgioSl": "3|1"
}
]
}
parser class:
public class JSONparser extends DBImplementManager {
ArrayList<Queryjson> jsonParseResult = new ArrayList<Queryjson>();
HashMap<String, Queryjson> _querymap = new HashMap<>();
public LinkedHashMap<String,Queryjson> _pgmValmap =new LinkedHashMap<String,Queryjson>();
private JSONparser()
{
//load(pgmid);
}
private static JSONparser instance;
public static JSONparser getInstance()
{
if(instance==null)
{
synchronized(JSONparser.class){
if(instance==null)
{
instance=new JSONparser();
}
}
}
return instance;
}
public void load(String pgmid, String modid)
{
try {
InputStream input = Thread.currentThread()
.getContextClassLoader().getResourceAsStream(path);
Reader reader = new InputStreamReader(input, "UTF-8");
jsonParseResult = new Gson().fromJson(reader, new TypeToken<List<Queryjson>>(){}.getType());
System.out.println("json loading begin");
if (jsonParseResult != null ) {
for (Queryjson _query : jsonParseResult) {
_querymap.put(_query.getCode(), _query);
_pgmValmap.put(pgmid+"_"+_query.getCode(), _query);
System.out.println("Result: " + _query.getCode());
// _query.loadmaps();
}
}
System.out.println("json loading done");
} catch (Exception e) {
e.printStackTrace();
}
}
}
pojo class:
public class Queryjson {
public Queryjson(){
}
private String code;
private String query;
private String type;
private String _condqflg;
private String _pkgvarflg;
private String _IOSerial;
private valIOConfigclass[] _ioConfig;
private valCFGclass[] _valcfg;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getQuery() {
return query;
}
public void setQuery(String query) {
this.query = query;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getcondqflg() {
return _condqflg;
}
public void setcondqflg(String _condqflg) {
this._condqflg = _condqflg;
}
public String getpkgvarflg() {
return _pkgvarflg;
}
public void setpkgvarflg(String _pkgvarflg) {
this._pkgvarflg = _pkgvarflg;
}
public String get_IOSerial() {
return _IOSerial;
}
public void set_IOSerial(String _IOSerial) {
this._IOSerial = _IOSerial;
}
public valIOConfigclass[] get_ioConfig() {
return _ioConfig;
}
public void set_ioConfig(valIOConfigclass[] _ioConfig) {
this._ioConfig = _ioConfig;
}
public valCFGclass[] get_valcfg() {
return _valcfg;
}
public void set_valcfg(valCFGclass[] _valcfg) {
this._valcfg = _valcfg;
}
public class valIOConfigclass {
private String _iosl;
private String _iokey;
private String _iotype;
private String _ioflag;
public valIOConfigclass()
{
}
public String get_iosl() {
return _iosl;
}
public void set_iosl(String _iosl) {
this._iosl = _iosl;
}
public String get_iokey() {
return _iokey;
}
public void set_iokey(String _iokey) {
this._iokey = _iokey;
}
public String get_iotype() {
return _iotype;
}
public void set_iotype(String _iotype) {
this._iotype = _iotype;
}
public String get_ioflag() {
return _ioflag;
}
public void set_ioflag(String _ioflag) {
this._ioflag = _ioflag;
}
}
public class valCFGclass{
private String _cfgsl;
private String _cfgstr;
private String _cfgioSl;
public valCFGclass(){
}
public String get_cfgsl() {
return _cfgsl;
}
public void set_cfgsl(String _cfgsl) {
this._cfgsl = _cfgsl;
}
public String get_cfgstr() {
return _cfgstr;
}
public void set_cfgstr(String _cfgstr) {
this._cfgstr = _cfgstr;
}
public String get_cfgioSl() {
return _cfgioSl;
}
public void set_cfgioSl(String _cfgioSl) {
this._cfgioSl = _cfgioSl;
}
}
}
Mark your inner classes (valIOConfigclass and valCFGclass) as static

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.

Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 5921 path $.data[5].courier.data

I have this model object Courier :
public class Courier {
#SerializedName("data")
private List<User> data = null;
public Courier() {
}
public Courier(List<User> data) {
this.data = data;
}
public List<User> getData() {
return data;
}
public void setData(List<User> data) {
this.data = data;
}
}
I get this response from server:
{
"data": [
{
"id": 446,
"courier": {
"data": []
},
"title": "гром",
"description": "Логойский тракт 24 в России в начале следующей",
"departure": "ChIJPQKUckNv2UYRLr1NasgXZ08",
"arrival": "EkHQodC10YDQtdCx0YDRj9C90YvQuSDQv9C10YDQtdGD0LvQvtC6LCDQnNC-0YHQutCy0LAsINCg0L7RgdGB0LjRjw"
},
{
"id": 438,
"courier": {
"data": []
},
"title": "тест",
"description": "гппг лмш ш ш ш ш г У меня на сковородке стоит ли брать сва в кино мы все равно обсуждаем",
"departure": "ChIJH10nmDnP20YR-n7Kq6Whd5w",
"arrival": "Ej_QnNC-0YHQutCy0L7RgNC10YbQutCw0Y8g0YPQu9C40YbQsCwg0JzQvtGB0LrQstCwLCDQoNC-0YHRgdC40Y8"
},
{
"id": 439,
"courier": {
"data": []
},
"title": "лаьаьаат",
"description": "лала слат алс ал ала ал кща да аьад",
"departure": "ChIJH7D4cTnP20YRKlzSCnP6Mak",
"arrival": "Ej_QnNC-0YHQutCy0L7RgNC10YbQutCw0Y8g0YPQu9C40YbQsCwg0JzQvtGB0LrQstCwLCDQoNC-0YHRgdC40Y8"
},
{
"id": 442,
"courier": {
"data": {
"id": 122,
"email": null,
"phone": "73339999999",
"photo": null,
"rating": 0
}
},
"title": "картошечка",
"description": "Крупная сортированная",
"departure": "ChIJnZRv1jnP20YRWiezW55d1tA",
"arrival": "ChIJpfH6UJtp1EYRlhM20g-jzF4"
}
]
}
If object courier not have data, i get array "data": [], if object courier has data, i get object :
"courier": {
"data": {
"id": 122,
"email": null,
"phone": "73339999999",
"photo": null,
"rating": 0
}
}
And then I get error... Please give me advice how handle this case in android application...
is one of the most common mistakes when you start to use JSON with a client, for android please refer to this tutorial to understand
the best source to understand this kind of mistake is to read this post
a canonical SO post.
Is better to read it and understand it, that asking for a simple solution because you will go really often into this error.
while deserializing, Gson was expecting a JSON object, but found a
JSON array
A JSON Object is wrapped by a {
A JSON Array is wrapped by a [
What you need is to adapt your class Courier, to deserialize in the right way the JSON response.
take in mind that; a JSON array become deserialized in java as a Collection type or an array type;
PLEASE notice that is confusing to use two times data
on top of everything, the first data is
public class MyPojo
{
private Data[] data;
public Data[] getData ()
{
return data;
}
public void setData (Data[] data)
{
this.data = data;
}
#Override
public String toString()
{
return "ClassPojo [data = "+data+"]";
}
}
Data.class
public class Data
{
private String id;
private String title;
private String description;
private Courier courier;
private String arrival;
private String departure;
public String getId ()
{
return id;
}
public void setId (String id)
{
this.id = id;
}
public String getTitle ()
{
return title;
}
public void setTitle (String title)
{
this.title = title;
}
public String getDescription ()
{
return description;
}
public void setDescription (String description)
{
this.description = description;
}
public Courier getCourier ()
{
return courier;
}
public void setCourier (Courier courier)
{
this.courier = courier;
}
public String getArrival ()
{
return arrival;
}
public void setArrival (String arrival)
{
this.arrival = arrival;
}
public String getDeparture ()
{
return departure;
}
public void setDeparture (String departure)
{
this.departure = departure;
}
#Override
public String toString()
{
return "ClassPojo [id = "+id+", title = "+title+", description = "+description+", courier = "+courier+", arrival = "+arrival+", departure = "+departure+"]";
}
}
Courier.class
public class Courier
{
private String[] data;
public String[] getData ()
{
return data;
}
public void setData (String[] data)
{
this.data = data;
}
#Override
public String toString()
{
return "ClassPojo [data = "+data+"]";
}
}
I suggest you just to create a class Data with fields id, email, etc. And make field Data data in the class Courier instead of a List<> data
EDIT: then you can use a JsonDeserializer. Just remove #SerializedName("data") over the Data field, so that the Json will not parse this field. Then create a class:
public class CourierDeserializer implements JsonDeserializer<Courier> {
#Override
public Courier deserialize(final JsonElement json, final Type type,
final JsonDeserializationContext context) {
Courier result = new Gson().fromJson(json, Courier.class);
try {
if (json != null) {
result.setData((Data) context.deserialize(json, Data.class));
}
} catch (JsonParseException e) {
result.setData(null);
}
return result;
}
}
and finally register it where you create your GsonBuilder:
GsonBuilder gson = new GsonBuilder();
gson.registerTypeAdapter(Courier.class, new CourierDeserializer());
mGson = gson.create();
builder.setConverter(new GsonConverter(mGson));
if you use Retrofit.

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

Categories

Resources