This is my list which is coming in response now I have to add the objects belonging to particular itemIds using Java ,
[
{
"data": 210,
"dataValue":100,
"itemIds": "60e53dee7a814f0001de3538"
},
{
"data": 220,
"dataValue":120,
"itemIds": "60e53dee7a814f0001de3538"
},
{
"data": 110,
"dataValue":130,
"itemIds": "60e53dee7a814f0001de3539"
}
]
Ouput Required ->
[
{
"data": 430,
"Values":100,
"itemIds": "60e53dee7a814f0001de3538"
},
{
"data": 110,
"dataValue":130,
"itemIds": "60e53dee7a814f0001de3539"
}
]
You could do something like this
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class ListElement {
public static void main(String[] args) {
List<ListElement> elements = new ArrayList<ListElement>();
elements.add(new ListElement(210, 100, "60e53dee7a814f0001de3538"));
elements.add(new ListElement(220, 120, "60e53dee7a814f0001de3538"));
elements.add(new ListElement(110, 130, "60e53dee7a814f0001de3539"));
System.out.println(elements);
Map<String, List<ListElement>> elementsByItemId = elements.stream() //
.collect(Collectors.groupingBy(ListElement::getItemId)); //
elements = elementsByItemId.entrySet().stream() //
.map(entry -> new ListElement( //
entry.getValue().stream().collect(Collectors.summingInt(ListElement::getData)), //
entry.getValue().stream().collect(Collectors.summingInt(ListElement::getDataValue)), //
entry.getKey())) //
.collect(Collectors.toList());
System.out.println(elements);
}
int data;
int dataValue;
String itemId;
public ListElement(int data, int dataValue, String itemId) {
this.data = data;
this.dataValue = dataValue;
this.itemId = itemId;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public int getDataValue() {
return dataValue;
}
public void setDataValue(int dataValue) {
this.dataValue = dataValue;
}
public String getItemId() {
return itemId;
}
public void setItemId(String itemId) {
this.itemId = itemId;
}
#Override
public String toString() {
return "ListElement [data=" + data + ", dataValue=" + dataValue + ", itemId=" + itemId + "]";
}
}
Here would be a not perfect example of how to do this. Maybe you can improve this solution to your liking. For simplicity it uses an inner class and exposed fields. I'm sure you will avoid doing this :)
It uses a custom aggregating operator and the reduce method of streams (see java stream reduce tutorial or java stream reduce doc)
private static BinaryOperator<Item> itemAggregator = (aggregatedResult, nextElement) -> {
aggregatedResult.data += nextElement.data;
aggregatedResult.dataValue += nextElement.dataValue;
return aggregatedResult;
};
public static void something(List<Item> initialItemList) {
Set<String> uniqueItemIds = initialItemList.stream()
.map(item -> item.itemId)
.collect(Collectors.toSet());
List<Item> resultList = uniqueItemIds.stream()
.map(itemId -> new Item(0, 0, itemId))
.collect(Collectors.toList());
resultList.forEach(
resultItem -> {
initialItemList.stream()
.filter(item -> item.itemId.equals(resultItem.itemId))
.reduce(resultItem, itemAggregator);
});
}
static class Item {
public int data;
public int dataValue;
public String itemId;
public Item(int data, int dataValue, String itemId) {
this.data = data;
this.dataValue = dataValue;
this.itemId = itemId;
}
}
But be aware, that using the reduce method can easily be done wrong (see avoid reduce if possible) and you have to check if it makes sense in your context.
Related
I'm quite new in JSON, I need a specific format of output JSON from Jackson API. Here is the output actually needed:
{
"0": {
"symbol": "B",
"count": 2,
"symbolIndex": [0, 0]
},
"1": {
"symbol": "B",
"count": 2,
"symbolIndex": [0, 0]
},
"2": {
"symbol": "B",
"count": 2,
"symbolIndex": [0, 0]
}
}
Consider that object names can vary (0,1,2,3,4,5....) and depends on the requirement and these can be only in incremental order. How can I use object to generate this JSON output in Java using Jackson API?
Update
So I have got the answer from Tom and the complete code is following:
MainClass.java
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class MainClass {
public static void main(String[] args) {
SymbolCounts symbolCounts = new SymbolCounts();
symbolCounts.add("0", new MySymbol("A", 2, new int[]{1,1}));
symbolCounts.add("1", new MySymbol("B", 2, new int[]{1,1}));
symbolCounts.add("2", new MySymbol("C", 2, new int[]{1,1}));
String str = getJSONResponse(symbolCounts);
System.out.println(str);
}
protected static String getJSONResponse(SymbolCounts responseData) {
String jsonStringResponse = "";
try {
ObjectMapper mapper = new ObjectMapper();
jsonStringResponse = mapper.writeValueAsString(responseData);
} catch (JsonProcessingException jsonProcessingException) {
System.out.println(jsonStringResponse);
}
return jsonStringResponse;
}
}
SymbolCounts.java
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.HashMap;
import java.util.Map;
import static com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL;
#JsonInclude(NON_NULL)
#JsonIgnoreProperties(ignoreUnknown=true)
public class SymbolCounts {
#JsonProperty("symbolCounts")
private Map<String, MySymbol> symbolMap = new HashMap<String, MySymbol>();
#JsonAnySetter
public void add(String key, MySymbol value) {
symbolMap.put(key, value);
}
public Map<String, MySymbol> getSymbolMap() {
return symbolMap;
}
public void setSymbolMap(Map<String, MySymbol> symbolMap) {
this.symbolMap = symbolMap;
}
#Override
public String toString() {
return "SymbolCounts{" +
"symbolMap=" + symbolMap +
'}';
}
}
MySymbol.java
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import java.util.Arrays;
import static com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL;
#JsonInclude(NON_NULL)
#JsonIgnoreProperties(ignoreUnknown=true)
public class MySymbol {
private String symbol;
private int count;
private int[] symbolIndex;
public MySymbol() {
}
public MySymbol(String symbol, int count, int[] symbolIndex) {
this.symbol = symbol;
this.count = count;
this.symbolIndex = symbolIndex;
}
public String getSymbol() {
return symbol;
}
public void setSymbol(String symbol) {
this.symbol = symbol;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public int[] getSymbolIndex() {
return symbolIndex;
}
public void setSymbolIndex(int[] symbolIndex) {
this.symbolIndex = symbolIndex;
}
#Override
public String toString() {
return "LineID{" +
"symbol='" + symbol + '\'' +
", count=" + count +
", symbolIndex=" + Arrays.toString(symbolIndex) +
'}';
}
}
You could do this by using a map and the #JsonAnySetter.
Your higher level class would look like:
private Map<String, MySymbol> symbolMap;
#JsonAnySetter
public void add(String key, MySymbol value) {
symbolMap.put(key, value);
}
Your MySymbol class would just be:
private String symbol;
private Integer count;
private Integer[] symbolIndex;
Then your end result would be a map where the keys are your numeric values as Strings and the values are your symbol objects.
{
"status": true,
"message": [
{
"ID": 1,
"TFrom": "b",
"TTo": "c"
},
{
"ID": 2,
"TFrom": "b",
"TTo": "c"
},
{
"ID": 3,
"TFrom": "b",
"TTo": "c"
}
]
}
This is my JSON result, I'm using Android/Java and what I want is to get each object in the "message" array separated in an array, because each one of them should be in a list item.
Which means my ListView is going to view the "message" content in lists.
It's more like this:
list1= [{"ID": 1, "TFrom": "b", "TTo": "c"}]
list2= [{"ID": 2, "TFrom": "b", "TTo": "c"}]
Message Object Class:
public class MessagesObject {
boolean status;
List<AMessage> message;
public List<AMessage> getMessage() {
return message;
}
public void setMessage(List<AMessage> message) {
this.message = message;
}
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
}
AMessage Class:
public class AMessage {
int ID;
String TFrom;
String TTo;
public int getID() {
return ID;
}
public void setID(int ID) {
this.ID = ID;
}
public String getTFrom() {
return TFrom;
}
public void setTFrom(String TFrom) {
this.TFrom = TFrom;
}
public String getTTo() {
return TTo;
}
public void setTTo(String TTo) {
this.TTo = TTo;
}
}
Usage :
String json="you json string";
MessagesObject messagesObject = new Gson().fromJson(jsonToParse, MessagesObject.class);
Ref Gson :
implementation 'com.google.code.gson:gson:2.8.2'
Output:
I'm not sure what you really want, but if you really would like to convert an array into list of arrays, ie.
[1, 2, 3] => [[1], [2], [3]]
You can use this code as a starting point.
List<List<T>> YOUR_LIST_OF_LISTS = message.stream().map((e) -> {
ArrayList<T> temp = new ArrayList<>();
temp.add(e);
return temp;
}).collect(Collectors.toList());
Replace T with some datatype you want, in your case probably JSONObject.
Not android specific, just java codes. I'm not sure why you would want to do something like this tho. Comment below if this is not what you intended.
JSONObject heroObject = data.getJSONObject("favorite");
JSONArray jarray=heroObject.getJSONArray("message");
ArrayList<HashMap<String,String>> array=new ArrayList<>();
//now looping through all the elements of the json array
for (int i = 0; i < jarray.length(); i++) {
//getting the json object of the particular index inside the array
JSONObject heroObject = jarray.getJSONObject(i);
HashMap<String,String> inner=new HashMap<String, String>();
inner.put("id", heroObject.getString("ID"));
inner.put("from", heroObject.getString("TFrom"));
inner.put("to", heroObject.getString("TTo"));
array.add(inner);
}
Use gson library. check below how to implement in project.
build.gradle
implementation 'com.google.code.gson:gson:2.7'
Then create MessageModel.java and MessageBaseModel.java.
MessageModel.java
public class MessageModel {
#SerializedName("ID")
int id;
#SerializedName("TFrom")
String tFrom;
#SerializedName("TTo")
String tTo;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String gettFrom() {
return tFrom;
}
public void settFrom(String tFrom) {
this.tFrom = tFrom;
}
public String gettTo() {
return tTo;
}
public void settTo(String tTo) {
this.tTo = tTo;
}
}
MessageBaseModel.java
public class MessageBaseModel {
#SerializedName("status")
boolean status;
#SerializedName("message")
ArrayList<MessageModel> messageModels = new ArrayList<>();
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
public ArrayList<MessageModel> getMessageModels() {
return messageModels;
}
public void setMessageModels(ArrayList<MessageModel> messageModels) {
this.messageModels = messageModels;
}
}
Use below code in your main activity:(note: result is your JSON result)
MessageBaseModel messageBaseModel=new Gson().fromJson(result.toString() , MessageBaseModel.class);
ArrayList<MessageModel> messageModels = MessageBaseModel.getMessageModels();
Check below example to get the output:
messageModels.get(0) is your first message object
messageModels.get(0).getId()=1
messageModels.get(0).gettFrom()=b
messageModels.get(1).getId()=2
messageModels.get(2).getId()=3
Sorry for my english.
Try this
List<Map<String,String>> list = new ArrayList<>();
try
{
JSONArray messageArray = response.getJSONArray("message");
for (int i = 0;i<messageArray.length(); i++)
{
Map<String,String> map = new HashMap<>();
JSONObject jsonObject = messageArray.getJSONObject(i);
Iterator<String> keys = jsonObject.keys();
while (keys.hasNext())
{
String key = keys.next();
String value = jsonObject.getString(key);
map.put(key,value);
}
list.add(map);
}
}
catch (JSONException e)
{
e.printStackTrace();
}
My JSON string.
{
"RateCardType": [{
"rate_id": 32,
"applianceId": 59,
"categoryId": 33,
"install_Price": 599,
"uninstall_Price": 0,
"gasRefill_Price": 0,
"repair_Price": 249,
"basicClean_Price": 0,
"deepClean_Price": 449,
"demo_Price": 500
},
{
"rate_id": 33,
"applianceId": 59,
"categoryId": 34,
"install_Price": 799,
"uninstall_Price": 0,
"gasRefill_Price": 0,
"repair_Price": 349,
"basicClean_Price": 0,
"deepClean_Price": 799,
"demo_Price": 500
}
]
}
MyRateCard.java
package com.example.demo;
import javax.persistence.Column;
public class MyRateCard {
#Column(name = "rate_id")
int rate_id;
public void setRate_id(int rate_id) {
this.rate_id=rate_id;
}
public int getRate_id() {
return rate_id;
}
#Column(name = "applianceId")
int applianceId;
public void setApplianceId(int applianceId {
this.applianceId=applianceId;
}
public int getApplianceId() {
return applianceId;
}
#Column(name = "categoryId")
int categoryId;
public void setCategoryId(int categoryId) {
this.categoryId=categoryId;
}
public int getCategoryId() {
return categoryId;
}
#Column(name = "install_Price")
int install_Price;
public void setInstall_Price(int install_Price {
this.install_Price=install_Price;
}
public int getInstall_Price() {
return install_Price;
}
#Column(name = "uninstall_Price")
int uninstall_Price;
public void setUninstall_Price(int uninstall_Price) {
this.uninstall_Price=uninstall_Price;
}
public int getUninstall_Price() {
return uninstall_Price;
}
#Column(name = "gasRefill_Price")
int gasRefill_Price;
public void setGasRefill_Price(int gasRefill_Price) {
this.gasRefill_Price=gasRefill_Price;
}
public int getGasRefill_Price() {
return gasRefill_Price;
}
#Column(name = "repair_Price")
int repair_Price;
public void setRepair_Price(int repair_Price) {
this.repair_Price=repair_Price;
}
public int getRepair_Price() {
return repair_Price;
}
#Column(name = "basicClean_Price")
int basicClean_Price;
public void setBasicClean_Price(int basicClean_Price) {
this.basicClean_Price=basicClean_Price;
}
public int getBasicClean_Price() {
return basicClean_Price;
}
#Column(name = "deepClean_Price")
int deepClean_Price;
public void setDeepClean_Price(int deepClean_price) {
this.deepClean_Price=deepClean_price;
}
public int getDeepClean_Price() {
return deepClean_Price;
}
#Column(name = "demo_Price")
int demo_Price;
public void setDemo_Price(int demo_Price) {
this.demo_Price=demo_Price;
}
public int getDemo_Price() {
return demo_Price;
}
}
I have created a model class MyRateCard.java with all getters and setters. I want to create a object for MyRateCard with first object in JSON string(say rate_id:32).
MyRateCard ratecard = new Gson().fromJson(response.toString(), MyRateCard.class);
But not working. Can someone help me to parse this?
{
"RateCardType": [{
"rate_id": 32,
"applianceId": 59,
"categoryId": 33,
"install_Price": 599,
"uninstall_Price": 0,
"gasRefill_Price": 0,
"repair_Price": 249,
"basicClean_Price": 0,
"deepClean_Price": 449,
"demo_Price": 500
},
{
"rate_id": 33,
"applianceId": 59,
"categoryId": 34,
"install_Price": 799,
"uninstall_Price": 0,
"gasRefill_Price": 0,
"repair_Price": 349,
"basicClean_Price": 0,
"deepClean_Price": 799,
"demo_Price": 500
}
]
}
This is your JSON. This is JSON is an Object which contains an array of RateCardType.
You have created the RateCardType class.
Now create a class which consists of List of MyRateCard class.
class ListRateCard {
List<MyRateCard> RateCardType;
// write getter and setter
}
Now, write the below code:
ListRateCard ratecards = new Gson().fromJson(response.toString(), ListRateCard.class);
Fetch rateId by the below code:
ratecards.getRateCardType().get(0).getRate_id();
These are 2 files.The MyPojo class is a holder for your actual data.In your json as you can the outer {} signifies an object,this object contains just 1 key called RateCardType.Hence the outer class called MyPojo.
Now the key RateCardType contains a list of objects as shown by the [] brackets,hence the List<RateCardType> .The rest is just data contained within the RateCardType class which you had got initially.
public class MyPojo
{
private List<RateCardType> RateCardType;
public List<RateCardType> getRateCardType ()
{
return RateCardType;
}
public void setRateCardType (List<RateCardType> RateCardType)
{
this.RateCardType = RateCardType;
}
}
public class RateCardType
{
private String repair_Price;
private String basicClean_Price;
private String uninstall_Price;
private String categoryId;
private String install_Price;
private String rate_id;
private String gasRefill_Price;
private String demo_Price;
private String deepClean_Price;
private String applianceId;
public String getRepair_Price ()
{
return repair_Price;
}
public void setRepair_Price (String repair_Price)
{
this.repair_Price = repair_Price;
}
public String getBasicClean_Price ()
{
return basicClean_Price;
}
public void setBasicClean_Price (String basicClean_Price)
{
this.basicClean_Price = basicClean_Price;
}
public String getUninstall_Price ()
{
return uninstall_Price;
}
public void setUninstall_Price (String uninstall_Price)
{
this.uninstall_Price = uninstall_Price;
}
public String getCategoryId ()
{
return categoryId;
}
public void setCategoryId (String categoryId)
{
this.categoryId = categoryId;
}
public String getInstall_Price ()
{
return install_Price;
}
public void setInstall_Price (String install_Price)
{
this.install_Price = install_Price;
}
public String getRate_id ()
{
return rate_id;
}
public void setRate_id (String rate_id)
{
this.rate_id = rate_id;
}
public String getGasRefill_Price ()
{
return gasRefill_Price;
}
public void setGasRefill_Price (String gasRefill_Price)
{
this.gasRefill_Price = gasRefill_Price;
}
public String getDemo_Price ()
{
return demo_Price;
}
public void setDemo_Price (String demo_Price)
{
this.demo_Price = demo_Price;
}
public String getDeepClean_Price ()
{
return deepClean_Price;
}
public void setDeepClean_Price (String deepClean_Price)
{
this.deepClean_Price = deepClean_Price;
}
public String getApplianceId ()
{
return applianceId;
}
public void setApplianceId (String applianceId)
{
this.applianceId = applianceId;
}
}
In order to use it
MyPojo holder= new Gson().fromJson(response.toString(), MyPojo.class);
List<RateCardType> list=holder.getRateCardType();
for(int i=0;i<list.size();i++)
{
list.get(i).getBasicClean_Price();
....
}
you can access any json level by tree hierachy
MyRateCard ratecard = new Gson().fromJson(response.toString(), MyRateCard.class);
String rateid=ratecard.rate_id;
My json string is:
{
"recordsTotal":1331,
"data":[
{
"part_number":"3DFN64G08VS8695 MS",
"part_type":"NAND Flash",
"id":1154,
"manufacturers":[
"3D-Plus"
]
},
{
"part_number":"3DPM0168-2",
"part_type":"System in a Package (SiP)",
"id":452,
"manufacturers":[
"3D-Plus"
]
},
{
"part_number":"3DSD1G16VS2620 SS",
"part_type":"SDRAM",
"id":269,
"manufacturers":[
"3D-Plus"
]
}
]
}
This code lets me access the two highest level elements:
JsonObject jsonObject = new JsonParser().parse(jsonString).getAsJsonObject();
System.out.println("data : " + jsonObject.get("data"));
System.out.println("recordsTotal : " + jsonObject.get("recordsTotal"));
But what I want to do is iterate over all the objects inside "data" and create a list of part_numbers. How do I do that?
JsonArray is an Iterable<JsonElement>. So you can use for in loop.
JsonObject jsonObject = new JsonParser().parse(jsonString).getAsJsonObject();
final JsonArray data = jsonObject.getAsJsonArray("data");
System.out.println("data : " + data);
System.out.println("recordsTotal : " + jsonObject.get("recordsTotal"));
List<String> list = new ArrayList<String>();
for (JsonElement element : data) {
list.add(((JsonObject) element).get("part_number").getAsString());
}
Suppose class Name for Json Model is Example.
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class Example {
#SerializedName("recordsTotal")
private Integer recordsTotal;
#SerializedName("data")
private List<Datum> data = null;
public Integer getRecordsTotal() {
return recordsTotal;
}
public void setRecordsTotal(Integer recordsTotal) {
this.recordsTotal = recordsTotal;
}
public List<Datum> getData() {
return data;
}
public void setData(List<Datum> data) {
this.data = data;
}
}
And suppose List of Data class name is Datum :-
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class Datum {
#SerializedName("part_number")
private String partNumber;
#SerializedName("part_type")
private String partType;
#SerializedName("id")
private Integer id;
#SerializedName("manufacturers")
private List<String> manufacturers = null;
public String getPartNumber() {
return partNumber;
}
public void setPartNumber(String partNumber) {
this.partNumber = partNumber;
}
public String getPartType() {
return partType;
}
public void setPartType(String partType) {
this.partType = partType;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public List<String> getManufacturers() {
return manufacturers;
}
public void setManufacturers(List<String> manufacturers) {
this.manufacturers = manufacturers;
}
}
And then through Gson library we can convert json to java Model :
Example example = new Gson().fromJson(jsonString, new TypeToken<Example>() {}.getType());
Now we can get list of data though example model :-
List<Datum> dataList = example.getData();
From dataList you can traverse and get all info.
If partNmber List we need then we can get in this way :-
List<String> partNumberList = new ArrayList<>();
for (Datum data : dataList) {
partNumberList.add(data.getPartNumber());
}
The given code will not guaranteed to 100% equivalent but it will help you to work.
First you have to create the class for your data objects:
class mydata {
public String part_name;
public String part_type;
public int Id;
public String manufacturers;
}
Your main method should look like
public static void main(String[] args) {
JSONObject obj = new JSONObject();
List<mydata> sList = new ArrayList<mydata>();
mydata obj1 = new mydata();
obj1.setValue("val1");
sList.add(obj1);
mydata obj2 = new mydata();
obj2.setValue("val2");
sList.add(obj2);
obj.put("list", sList);
JSONArray jArray = obj.getJSONArray("list");
for(int ii=0; ii < jArray.length(); ii++)
System.out.println(jArray.getJSONObject(ii).getString("value"));
}
For futher exploration you can use that link:
https://gist.github.com/codebutler/2339666
I'm getting the following error when using an ObjectMapper to de-serialize an object:
JSONMappingException Can not construct instance of
org.springframework.data.Page, problem: abstract types can only be
instantiated with additional type information.
I am trying to serialize a JSON string into a Spring data object org.springframework.data.Page which represents a page of type T.
The User class is a simple POJO with first and last name. The JSON string I am deserializing is:
{
"content": [
{
"firstname": "John",
"lastname": "Doe"
},
{
"firstname": "Jane",
"lastname": "Doe"
}
],
"size": 2,
"number": 0,
"sort": [
{
"direction": "DESC",
"property": "timestamp",
"ascending": false
}
],
"totalPages": 150,
"numberOfElements": 100,
"totalElements": 15000,
"firstPage": true,
"lastPage": false
}
This causes the exception:
Page<User> userPage = (Page<User>) new ObjectMapper().mapToJavaObject(json, new TypeReference<Page<User>>(){};
Since Page is a Spring object I cannot modify it which I think makes this a bit different from the way I see this question asked elsewhere. Any thoughts?
I ended up using something like this, creating a bean as #Perception suggested:
import java.util.ArrayList;
import java.util.List;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
public class PageImplBean<T> extends PageImpl<T> {
private static final long serialVersionUID = 1L;
private int number;
private int size;
private int totalPages;
private int numberOfElements;
private long totalElements;
private boolean previousPage;
private boolean firstPage;
private boolean nextPage;
private boolean lastPage;
private List<T> content;
private Sort sort;
public PageImplBean() {
super(new ArrayList<T>());
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public int getTotalPages() {
return totalPages;
}
public void setTotalPages(int totalPages) {
this.totalPages = totalPages;
}
public int getNumberOfElements() {
return numberOfElements;
}
public void setNumberOfElements(int numberOfElements) {
this.numberOfElements = numberOfElements;
}
public long getTotalElements() {
return totalElements;
}
public void setTotalElements(long totalElements) {
this.totalElements = totalElements;
}
public boolean isPreviousPage() {
return previousPage;
}
public void setPreviousPage(boolean previousPage) {
this.previousPage = previousPage;
}
public boolean isFirstPage() {
return firstPage;
}
public void setFirstPage(boolean firstPage) {
this.firstPage = firstPage;
}
public boolean isNextPage() {
return nextPage;
}
public void setNextPage(boolean nextPage) {
this.nextPage = nextPage;
}
public boolean isLastPage() {
return lastPage;
}
public void setLastPage(boolean lastPage) {
this.lastPage = lastPage;
}
public List<T> getContent() {
return content;
}
public void setContent(List<T> content) {
this.content = content;
}
public Sort getSort() {
return sort;
}
public void setSort(Sort sort) {
this.sort = sort;
}
public PageImpl<T> pageImpl() {
return new PageImpl<T>(getContent(), new PageRequest(getNumber(),
getSize(), getSort()), getTotalElements());
}
}
and then modify your code to use the concrete class and get the PageImpl:
#SuppressWarnings("unchecked")
Page<User> userPage = ((PageImplBean<User>)new ObjectMapper().readValue(json, new TypeReference<PageImplBean<User>>() {})).pageImpl();
You can do this:
public class YourClass {
static class CustomPage extends PageImpl<User> {
#JsonCreator(mode = Mode.PROPERTIES)
public CustomPage(#JsonProperty("content") List<User> content, #JsonProperty("number") int page, #JsonProperty("size") int size, #JsonProperty("totalElements") long total) {
super(content, new PageRequest(page, size), total);
}
}
public Page<User> makeRequest(String json) {
Page<User> pg = new ObjectMapper().readValue(json, CustomPage.class);
return pg;
}
}