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"
}
]
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 want n number that means my last record of the ArrayList but the problem is my ArrayList is of custom POJO class which contains its own array that's why i am unable to identify how many records that ArrayList contains
Please check below my JSON from which I am creating a POJO class
{
"data": [
{
"id": "7",
"name": "Grand Father Name",
"parent_id": "0",
"relation_type": "grand-father",
"children": [
]
},
{
"id": "8",
"name": "Grand Mother Name",
"parent_id": "0",
"relation_type": "grand-mother",
"children": [
{
"id": "9",
"name": "Father Name",
"parent_id": "8",
"relation_type": "father",
"children": [
{
"id": "11",
"name": "My Name",
"parent_id": "9",
"relation_type": "self",
"children": [
]
}
]
},
{
"id": "10",
"name": "Mother Name",
"parent_id": "8",
"relation_type": "mother",
"children": [
]
}
]
}
]
}
POJO class
public class Tree {
#SerializedName("data")
#Expose
public ArrayList<Child> data = null;
public class Child {
#SerializedName("family_id")
#Expose
public int family_id;
#SerializedName("name")
#Expose
public String name;
#SerializedName("relation_type")
#Expose
public String relation_type;
#SerializedName("parent_id")
#Expose
public int parentId;
#SerializedName("children")
#Expose
public List<Child> children = null;
public int getId() {
return family_id;
}
public void setId(int id) {
this.family_id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getParentId() {
return parentId;
}
public void setParentId(int parentId) {
this.parentId = parentId;
}
public List<Child> getChildren() {
return children;
}
public void setChildren(List<Child> children) {
this.children = children;
}
}
}
As you can see Child class contains a List of its own so I am unable to identify how many records this list will contain
Hope it clears my problem any help will be appreciated.
Thanks in advance
You can do this recursively:
ArrayList<Child> list = new ArrayList<>(); //this is the list where you want to fill all children
void fillRecursively(ArrayList<Child> root){
List<Child> children = root.getChildren();
for(Child child : children){
if(child.getChildren().size()!=0){
fillRecursively(child);
}else{
list.add(child);
}
}
}
}
Also don't forget to add your root node to the list.
list.add(root); //at the beginning
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'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;
}
}
I am trying to implement PagingAndSortingRepository from spring boot data REST.
It certainly does return a paged response, however i cant find a way to get it to display navigation links between pages. I have looked at quite a few tutorials and documentation on this, and it seems that it should just happen as a consequence of using the PagingAndSortingRepository that is provided.
Please advise me someone! it should be so simple.
Thanks in advance.
Classes:
#RestController
public class CommentController {
private final CommentFacade facade;
#Autowired
public CommentController(CommentRepository commentdao) {
this.facade = new CommentFacadeImpl(commentdao);
}
#RequestMapping(value = "/comments", method = RequestMethod.GET)
public PagedResources<Resource<Comment>> getPagedList(#RequestParam(value = "user-id", required = true) Long userId) {
Pageable pageable = new PageRequest(1, 10);
Page<Comment> commentsList = facade.findAll(pageable);
List<Resource<Comment>> resourceList = new ArrayList<>();
for (Comment comment : commentsList) {
Resource<Comment> commentResource = new Resource<>(comment);
commentResource.add(linkTo(methodOn(CommentController.class)
.getSpecificComment(comment.getId())).withSelfRel());
resourceList.add(commentResource);
}
PagedResources<Resource<Comment>> resources = new PagedResources<>(resourceList,
new PageMetadata(commentsList.getNumber(), commentsList.getTotalElements(), commentsList.getTotalPages(), 5),
linkTo(methodOn(CommentController.class)
.getPagedList(userId)).withSelfRel());
return resources;
}
}
#RepositoryRestResource
public interface CommentRepository extends PagingAndSortingRepository<Comment, Long> {
Page findAll(Pageable pageRequest);
}
#Entity
#Table(name="comment")
#EnableEntityLinks
#RepositoryRestResource
public class Comment {
#Id
#GeneratedValue(strategy= GenerationType.AUTO)
#Column(name="id")
private #JsonIgnore Long id;
#Column(name="created")
private Date created;
#Column(name="latitude")
private #JsonIgnore Float latitude;
#Column(name="longitude")
private #JsonIgnore Float longitude;
#Column(name="ip")
private #JsonIgnore String ip;
#Column(name="text")
private String comment;
#Column(name="sender_id")
private Long senderId;
#JsonIgnore
private Long postId;
#JsonIgnore
#Column(name="deleted")
private Boolean deleted;
protected Comment() {};
public Comment(String comment, Long senderId, Long post_id) {
this.id = null;
this.created = new Date();
this.latitude = 12.1111111138563456f;
this.longitude = -17.444333333333f;
this.ip = "34.6.5.213";
this.comment = "some comment";
this.senderId = 1L;
this.postId = post_id;
this.deleted = false;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public Float getLatitude() {
return latitude;
}
public void setLatitude(Float latitude) {
this.latitude = latitude;
}
public Float getLongitude() {
return longitude;
}
public void setLongitude(Float longitude) {
this.longitude = longitude;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public Long getSenderId() {
return senderId;
}
public void setSenderId(Long senderId) {
this.senderId = senderId;
}
#ManyToOne
#JoinColumn(name = "post_id")
#JoinTable(name = "post")
public Long getPostId() {
return postId;
}
public void setPostId(Long postId) {
this.postId = postId;
}
public Boolean getDeleted() {
return deleted;
}
public void setDeleted(Boolean deleted) {
this.deleted = deleted;
}
}
My JSON HAL output:
{
"_embedded": {
"commentList": [
{
"created": 1468176648000,
"comment": "some comment",
"senderId": 1,
"_links": {
"self": {
"href": "http://localhost:8090/comments/11"
}
}
},
{
"created": 1468176649000,
"comment": "some comment",
"senderId": 1,
"_links": {
"self": {
"href": "http://localhost:8090/comments/12"
}
}
},
{
"created": 1468176650000,
"comment": "some comment",
"senderId": 1,
"_links": {
"self": {
"href": "http://localhost:8090/comments/13"
}
}
},
{
"created": 1468176650000,
"comment": "some comment",
"senderId": 1,
"_links": {
"self": {
"href": "http://localhost:8090/comments/14"
}
}
},
{
"created": 1468176651000,
"comment": "some comment",
"senderId": 1,
"_links": {
"self": {
"href": "http://localhost:8090/comments/15"
}
}
},
{
"created": 1468176651000,
"comment": "some comment",
"senderId": 1,
"_links": {
"self": {
"href": "http://localhost:8090/comments/16"
}
}
},
{
"created": 1468176678000,
"comment": "some comment",
"senderId": 1,
"_links": {
"self": {
"href": "http://localhost:8090/comments/17"
}
}
},
{
"created": 1468176679000,
"comment": "some comment",
"senderId": 1,
"_links": {
"self": {
"href": "http://localhost:8090/comments/18"
}
}
},
{
"created": 1468176679000,
"comment": "some comment",
"senderId": 1,
"_links": {
"self": {
"href": "http://localhost:8090/comments/19"
}
}
},
{
"created": 1468176680000,
"comment": "some comment",
"senderId": 1,
"_links": {
"self": {
"href": "http://localhost:8090/comments/20"
}
}
}
]
},
"_links": {
"self": {
"href": "http://localhost:8090/comments?user-id=1"
}
},
"page": {
"size": 1,
"totalElements": 4,
"totalPages": 5,
"number": 38
}
}
Seems to work, but no navigation links. Any ideas?
The links are added by PagedResourcesAssembler which you need to use to create the PagedResources manually in the first place.
If you're using Spring Data REST, you don't need any of the controller code at all and can let Spring Data REST create the resources for you. See this getting started guide for a sample.