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;
}
}
Related
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
I have a json string like this.
[
{
"_source": {
"name": "Jam Brong",
"image": "https://asdf.asdf.com/asdf/image/upload/w_30,h_30,c_fill/product/fb7d3dcb505fba76262c0c6383d844ae.jpg",
"price": "2500",
"slug": "133-jam-brong",
"short_name": "Jam Brong"
}
},
{
"_source": {
"name": "Jam abcfdfjn",
"image": "https://asdf.asdf.com/asdf/image/upload/w_30,h_30,c_fill/product/7bbd3d081dd03c442e4cb27321a7b50c.jpg",
"price": "10888",
"slug": "87-jam-abcfdfjn",
"short_name": "Jam abcfdfjn"
}
}
]
I need to remove "_source":{
so i can get a json string like this.
[
{
"name": "Jam Brong",
"image": "https://asdf.asdf.com/asdf/image/upload/w_30,h_30,c_fill/product/fb7d3dcb505fba76262c0c6383d844ae.jpg",
"price": "2500",
"slug": "133-jam-brong",
"short_name": "Jam Brong"
},
{
"name": "Jam abcfdfjn",
"image": "https://asdf.asdf.com/asdf/image/upload/w_30,h_30,c_fill/product/7bbd3d081dd03c442e4cb27321a7b50c.jpg",
"price": "10888",
"slug": "87-jam-abcfdfjn",
"short_name": "Jam abcfdfjn"
}
]
I tried to use replaceAll("("_source:{"),"");
This code will show me some error like number expected.
I don't know how to use regex for the string which contains _ and { .
Before i think to use replaceAll, i tried jackson like this.
String responses ="";
ObjectNode node = new ObjectMapper().readValue(response.toString(), ObjectNode.class);
ProductList productListInstance = new ProductList();
List<Product> productList = new ArrayList<>();
try {
if(node.get("hits").get("hits").isArray()){
for (final JsonNode objNode : node.get("hits").get("hits")) {
Product products = new ObjectMapper().readValue(objNode.get("_source").toString(), Product.class);
productList.add(products);
}
productListInstance.setProductList(productList);
}
responses = productListInstance.toString();
}
catch (Exception ex){
responses = productListInstance.toString();
}
return responses;
actually the first json string was like this :
{
"hits": {
"hits": [
{
"_source": {
"name": "Jam Brong",
"image": "https://asdf.asdf.com/asdf/image/upload/w_30,h_30,c_fill/product/fb7d3dcb505fba76262c0c6383d844ae.jpg",
"price": "2500",
"slug": "133-jam-brong",
"short_name": "Jam Brong"
}
},
{
"_source": {
"name": "Jam abcfdfjn",
"image": "https://asdf.sdf.com/asdf/image/upload/w_30,h_30,c_fill/product/7bbd3d081dd03c442e4cb27321a7b50c.jpg",
"price": "10888",
"slug": "87-jam-abcfdfjn",
"short_name": "Jam abcfdfjn"
}
}
]
}
}
You can use Jackson to achieve this. First, define a bean representing your data model.
public static class Source {
private String name;
private String image;
private String price;
private String slug;
private String shortName;
#JsonCreator
public Source(#JsonProperty("_source") Map<String, Object> rawJson) {
this.name = rawJson.get("name").toString();
this.image = rawJson.get("image").toString();
this.price = rawJson.get("price").toString();
this.slug = rawJson.get("slug").toString();
this.shortName = rawJson.get("short_name").toString();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getSlug() {
return slug;
}
public void setSlug(String slug) {
this.slug = slug;
}
public String getShortName() {
return shortName;
}
public void setShortName(String shortName) {
this.shortName = shortName;
}
}
Observe the #JsonCreator annotation on the constructor. Then write the code for serialization and deserialization:
final ObjectMapper mapper = new ObjectMapper();
Source[] sources = mapper.readValue(jsonStr, Source[].class);
String converted = mapper.writeValueAsString(sources);
System.out.println(converted);
Prints:
[
{
"name": "Jam Brong",
"image": "https://asdf.asdf.com/asdf/image/upload/w_30,h_30,c_fill/product/fb7d3dcb505fba76262c0c6383d844ae.jpg",
"price": "2500",
"slug": "133-jam-brong",
"shortName": "Jam Brong"
},
{
"name": "Jam abcfdfjn",
"image": "https://asdf.asdf.com/asdf/image/upload/w_30,h_30,c_fill/product/7bbd3d081dd03c442e4cb27321a7b50c.jpg",
"price": "10888",
"slug": "87-jam-abcfdfjn",
"shortName": "Jam abcfdfjn"
}
]
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;}
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.
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.