I have the json return from server like this:
[{"id":1,"group":[{"id":1,"subGroup":[{"id":1,"item":"X"}]}]}]
how to I get the arrays group and subgroup?
I'm using restlet on Android Client.
thanks all.
String mResponse = "[{"id":1,"group":[{"id":1,"subGroup":[{"id":1,"item":"X"}]}]}]";
JSONArray responseArrayJson = new JSONArray(mResponse); // This creates a JSON array from your response string.
JSONObject objectJson = responseArrayJson.getJSONObject(0); // gets the one and only JSON object in your array.
JSONArray groupArrayJson = objectJson.getJSONArray("group"); // gets the array indexed by "group".
You can repeat this pattern to get "subGroup" as well.
I solved this problem as follows:
first change the json of server:
from:
[{"id":1,"group":[{"id":1,"subGroup":[{"id":1,"item":"X"}]}]}]
to
{"array":[{"id":1,"group":[{"id":1,"subGroup":[{"id":1,"item":"X"}]}]}]}
Second in Android client I make this:
a class to get first array, the class ServerModel with firstArray "array":
public class ServerModel implements Serializable {
private static final long serialVersionUID = 1L;
private FirstArray[] array;
public ServerModel() {
}
public ServerModel(FirstArray[] array) {
this.array = array;
}
}
third the class with secondArray "group":
public class FirstArray implements Serializable {
private static final long serialVersionUID = 1L;
private SecondArray[] group;
private int id;
public FirstArray() {
}
public FirstArray(int id, SecondArray[] group) {
this.id = id;
this.group = group;
}
}
fourth the class with thirdArray "subGroup":
public class SecondArray implements Serializable {
private static final long serialVersionUID = 1L;
private Itens[] subGroup;
private int id;
public SecondArray() {
}
public SecondArray(int id, Itens[] subGroup) {
this.id = id;
this.subGroup = subGroup;
}
}
and in the last the class of itens "item"
public class Itens implements Serializable {
private static final long serialVersionUID = 1L;
private String item;
private int id;
public Itens() {
}
public Itens(int id, String item) {
this.id = id;
this.item = item;
}
}
thanks all for help!!!
Related
list = [{"tools":12,"id":1,"time":"2020-09-28"}, {"tools":11,"id":4,"time":"2021-10-24"}, {"tools":18,"id":3,"time":"2019-09-24"}]
//sort the list by "id" and "time"
you can use Java8 grammar,Stream as follow:
public static void main(String[] args) {
ArrayList<Sorting> list = new ArrayList<>();
List<Sorting> result = list.stream().sorted(Comparator.comparing(Sorting::getId).thenComparing(Sorting::getTime)).collect(Collectors.toList());
}
//Demo class
static class Sorting{
private Integer id;
private Integer tools;
private LocalDateTime time;
public Integer getId() {
return id;
}
public Integer getTools() {
return tools;
}
public LocalDateTime getTime() {
return time;
}
}
public class Call {
private String status;
private String callName;
private int duration;
private int waitedTime;
}
I have a list of calls and i have to create a summary, like this:
public class CallSummary {
private String callName;
private List<ItemSummary> items;
private int averageDuration;
private int averageWaitedTime
}
public class itemSummary {
private String status;
private Integer percentage;
}
My goal is show a summary like :
{
callname:"sac",
averageDuration:"60",
averageWaitedTime:"10",
items:{
status:"failed",
percentage:"40"
status:"answered","60"
}
}
how can i do it using java 8 stream and Collectors ?
I have two classes, my object class, and the ListObjectClass.
In my constructor of ListObjectClass I create an array of an object looking like this:
private ObjectClass[] name;
And I have to make an ID for each ObjectClass, but I don't know how can I do that, do I need to make a getID() and setID() on ObjectClass?
Constructor of ListObject Class:
private int id;
private float pes;
private int nRegistres;
private RellotgeObjecte[] rellotge;
public LlistaRegistreEsportiu(int n) {
this.nRegistres = 0;
rellotge = new RellotgeObjecte[n];
}
You can pass the ID as an argument of the constructor:
public LlistaRegistreEsportiu(int n, int id) {
this.nRegistres = 0;
rellotge = new RellotgeObjecte[n];
this.id = id;
}
I'm using spring boot to create a web service.
I'm trying to introduce HATEOAS to an endpoint. Here's the model(DTO):
public class MovieResponse {
private Long id;
private String name;
private Date releaseDate;
private Time runtime;
private Float rating;
private String storyline;
private String poster;
private String rated;
private Date createdAt;
private List<GenreResponse> genres = new ArrayList<>();
private List<MovieMediaResponse> videos = new ArrayList<>();
private List<MovieMediaResponse> photos = new ArrayList<>();
private List<MovieReviewResponse> reviews = new ArrayList<>();
private List<MovieCelebrityResponse> cast = new ArrayList<>();
private List<MovieCelebrityResponse> writers = new ArrayList<>();
private List<MovieCelebrityResponse> directors = new ArrayList<>();
// Getters & Setters
}
Also i have a PagedResponse which holds the page information:
public class PagedResponse<T> {
private List<T> content;
private int page;
private int size;
private long totalElements;
private int totalPages;
private boolean last;
public PagedResponse() {}
public PagedResponse(List<T> content, int page, int size, long totalElements, int totalPages, boolean last) {
this.content = content;
this.page = page;
this.size = size;
this.totalElements = totalElements;
this.totalPages = totalPages;
this.last = last;
}
// Getters & Setters
}
I also have getAllMovies method in the service which return PagedResponse<MovieResponse>.
Now here's MovieResourceAssembler
#Component
public class MovieResourceAssembler implements ResourceAssembler<MovieResponse, Resource<MovieResponse>> {
private EntityLinks entityLinks;
#Autowired
public void setEntityLinks(EntityLinks entityLinks) {
this.entityLinks = entityLinks;
}
#Override
public Resource<MovieResponse> toResource(MovieResponse movieResponse) {
Link self = entityLinks.linkFor(MovieResponse.class).slash(movieResponse.getId()).withSelfRel();
Link rel = entityLinks.linkFor(MovieResponse.class).slash(movieResponse.getId()).withRel("movie");
Link movieGenres = entityLinks.linkFor(MovieResponse.class).slash(movieResponse.getId()).slash("movieGenres").withRel("movieGenres");
Link movieReviews = entityLinks.linkFor(MovieResponse.class).slash(movieResponse.getId()).slash("movieReviews").withRel("movieReviews");
return new Resource<>(movieResponse, self, rel, movieGenres, movieReviewsa);
}
}
When i try to use it in my controller like the following :
#RestController
public class MovieController {
private MovieService movieService;
private PagedResourcesAssembler<MovieResponse> pagedAssembler;
private MovieResourceAssembler movieResourceAssembler;
#Autowired
public MovieController(MovieService movieService, PagedResourcesAssembler<MovieResponse> pagedAssembler, MovieResourceAssembler movieResourceAssembler) {
this.movieService = movieService;
this.pagedAssembler = pagedAssembler;
this.movieResourceAssembler = movieResourceAssembler;
}
#GetMapping("/movies")
public ResponseEntity<?> getAllMovies(#RequestParam(value = "page", defaultValue = DEFAULT_PAGE_NUMBER) String page,
#RequestParam(value = "size", defaultValue = DEFAULT_PAGE_SIZE) String size,
#RequestParam(value = "sort", defaultValue = "createdAt") String sort,
#RequestParam(value = "direction", defaultValue = "desc") String direction) {
PagedResponse<MovieResponse> response = this.movieService.getAllMovies(page, size, sort, direction);
return ResponseEntity.ok(this.pagedAssembler.toResource(response, this.movieResourceAssembler));
}
}
got the following Error:
Cannot resolve method 'toResource(com.movies.mmdb.util.PagedResponse, com.movies.mmdb.controller.MovieResourceAssembler)'
in this line: return ResponseEntity.ok(this.pagedAssembler.toResource(response, this.movieResourceAssembler));
i think toResource accept org.springframework.data.domain.Page; while i'm passing response variable which is PagedResponse.
How can i fix that ?
If toResource method receives a Page<T> as the first parameter, then why don't you use that data type? If you need to extend Page then your class should implement such interface to fulfill the method signature:
public class PagedResponse<T> implements Page<MovieResponse>
I would like to map a field with nested collection using Orika library. My field in class is defined as:
private final List<List<Pojo>> list = new LinkedList<List<Pojo>>();
Pojo is a simple POJO class. Unfortunately I've got a MappingException caused by NullPointerException in Orika's internal logic.
Did I do something in wrong way? Maybe I need to use Custom Mapping feature?
EDIT:
Here is my code:
public class Pojo {
private int field;
public int getField() {
return field;
}
public void setField(final int field) {
this.field = field;
}
}
public class Source {
private final List> list = new LinkedList>();
public List<List<Pojo>> getList() {
return list;
}
}
public class Destination {
private final List> listDest = new LinkedList>();
public List<List<Pojo>> getListDest() {
return listDest;
}
}
public class Main {
public static void main(final String[] args) {
final MapperFactory factory = new DefaultMapperFactory.Builder().build();
factory.classMap(Source.class, Destination.class).field("list", "listDest").byDefault().register();
final Source src = new Source();
final LinkedList<Pojo> nestedList = new LinkedList<Pojo>();
final Pojo pojo = new Pojo();
pojo.setField(8978);
nestedList.add(pojo);
src.getList().add(nestedList);
final MapperFacade facade = factory.getMapperFacade();
final Destination dest = facade.map(src, Destination.class);
System.out.println(dest.getListDest().get(0).get(0).getField());
}
}
Execution above code results this Exception:
Exception in thread "main" ma.glasnost.orika.MappingException: Error encountered while mapping for the following inputs:
rawSource=com.bbh.nested.Source#39185ce6
sourceClass=class com.bbh.nested.Source
destinationClass=class com.bbh.nested.Destination
You can see this Example:
public class ShopEntity {
private Long id;
private String name;
private String logo;
private String url;
private ProductCategory mainCategory;
private Set<ShopRel> shopRels = new HashSet<>(0);
private Account account;
// Assume getter/setter
}
public class ProductCategory extends BaseEntity {
private Long id;
private String name;
// Assume getter/setter
}
public class ShopRel {
private Long id;
private SaleChannel saleChannel;
private Boolean enabled;
// Assume getter/setter
}
public class SaleChannel {
private Long id;
private String name;
private String image;
private String description;
private Boolean active;
// Assume getter/setter
}
public class ShopDto {
private Long id;
private String name;
private String logo;
private String url;
private Long mainCategory;
private Set<ShopRelDto> shopRelDtos = new HashSet<ShopRelDto>();
// Assume getter/setter
}
public class ShopRelDto {
private Long channelId;
private String name;
private Boolean enabled;
// Assume getter/setter
}
public class MapperUtils {
private static final MapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();
private static final MapperFacade mapper = mapperFactory.getMapperFacade();
static {
mapperFactory.classMap(ShopEntity.class, ShopDto.class)
.field("mainCategory.id", "mainCategory")
.fieldMap("shopRels", "shopRelDtos").aElementType(ShopRel.class).bElementType(ShopRelDto.class).add()
.register();
mapperFactory.classMap(ShopRel.class, ShopRelDto.class)
.field("saleChannel.id", "channelId")
.field("saleChannel.name", "name")
.field("enabled", "enabled")
.register();
}
public static final void map(Object source, Object distance) {
mapper.map(source, distance);
}
public static final <T> T map(Object source, Class<T> destinationClass){
return mapper.map(source, destinationClass);
}
public static void main(String[] args) {
ShopEntity shop = new ShopEntity();
shop.setId(1L);
shop.setName("ABC");
ProductCategory productCategory =new ProductCategory();
productCategory.setId(10L);
shop.setMainCategory(productCategory);
Set<ShopRel> shopRels = new HashSet<>(0);
ShopSaleChannelRel channelRel = new ShopSaleChannelRel();
channelRel.setId(1L);
channelRel.setEnabled(true);
SaleChannel saleChannel = new SaleChannel();
saleChannel.setId(1L);
saleChannel.setName("Channel1");
channelRel.setSaleChannel(saleChannel);
shopRels.add(channelRel);
shop.setShopRels(shopRels);
ShopDto shopDto = map(shop, ShopDto.class);
System.out.println(shopDto);
}
}
It may need a custom mapping via customize if there is lot of cases like this you can extend Orika via Specifications to support this use case