[英]Return only some values in json instead full entity object
我在JPA中從我的RESTful應用程序創建響應時遇到問題。 這就像是對Filmaffinty或imbd網站的模擬。
我只想返回電影中的特定值(ID,年份,名稱)。 我也想返回項目搜索的值(如果是電影MOVIE,是tv_show SERIE)。 該值不是實體的屬性。
import com.fasterxml.jackson.annotation.JsonProperty;
@Path("/search")
@RequestScoped
public class SearchRESTService extends RESTService {
@EJB
MovieService ms;
@EJB
ListMovieService lms;
@EJB
SeriaService ss;
@GET
@Path("/")
@Produces(MediaType.APPLICATION_JSON)
public Response search(@Context HttpServletRequest req) {
if (!checkLoggedIn(req)) {
throw new WebApplicationException("User not logged.");
}
String name = req.getParameter("n_name");
String typeFilter = req.getParameter("movie");
SearchResult sr = new SearchResult();
sr.movies = ms.getAllMovies();
switch (typeFilter){
case "movie":
sr.movies = ms.getMovieByName(name);
break;
/*case "tv_show":
sr.series = ms.getSeriesByName(name);
break;
*/
}
return buildResponse(sr);
}
static class SearchResult {
@JsonProperty("Movies")
Collection<Movie> movies;
@JsonProperty("List_Movies")
Collection<ListMovie> listMovies;
@JsonProperty("Series")
Collection<Seria> series;
}
}
是否可以向JSON添加“新值”。 我的意思是,我有電影類,我想將項目搜索的類型返回到JSON。 示例:如果我搜索電影,則JSON必須返回itemType =電影,如果它是tv_show,則itemType =系列
例如,如果我搜索泰坦尼克號,這應該是我的JSON:
{
"id": 18926,
"name": "Titanic",
"itemType": "Movie",
"year": 1997
}
不要修改JSON-只是返回對象的呈現。
而是,返回不同的對象類型,也許是SearchResult
對象。 根據需要創建,填充,修改它,然后讓JSON庫完成它的工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.