【问题标题】:How to exclude other class objects in a GET request? - Java Spring Boot如何在 GET 请求中排除其他类对象? - Java 春季启动
【发布时间】:2019-07-26 05:58:16
【问题描述】:

我正在编写一个简单的 GameShop Spring Boot CRUD 服务应用程序。我有 3 类游戏,客户,订单。 Order 类同时具有 Game 和 Customer 对象。

public class Game {

    @JsonView(View.Summary.class)
    private int id;
    @JsonView(View.Summary.class)
    private String name;
    private String genre;
    private String platform;
    @JsonView(View.Summary.class)
    private String price;
    private String developer;
}

public class Customer {

    @JsonView(View.Summary.class)
    private int id;
    @JsonView(View.Summary.class)
    private String name;
    @JsonView(View.Summary.class)
    private String email;
    private String phoneNumber;
}

public class Order {

    @JsonView(View.Summary.class)
    private int id;
    @JsonView(View.Summary.class)
    private Date orderDate; // Mby string idk
    @JsonView(View.Summary.class)
    private boolean completed;
    private Game game;
    private Customer customer;
}

问题是,当我发出像 http://localhost:8080/orders 这样的 GET 请求时,它会响应包含的 Game 和 Customer 对象,如下所示:

"_embedded": {
    "orderList": [
        {
            "id": 1,
            "orderDate": "2019-03-04T20:12:20.207+0000",
            "completed": false,
            "game": {
                "id": 1,
                "name": "Persona 5",
                "genre": "JRPG",
                "platform": "PS4",
                "price": "59.99",
                "developer": "Atlus"
            },
            "customer": {
                "id": 1,
                "name": "Jonas",
                "email": "Jonas123@gmail.com",
                "phoneNumber": "867492455"
            }
        },
        {
            "id": 2,
            "orderDate": "2019-03-04T20:12:20.207+0000",
            "completed": false,
            "game": {
                "id": 2,
                "name": "Red dead redemption 2",
                "genre": "Action Adventure",
                "platform": "PS4",
                "price": "59.99",
                "developer": "Rockstar"
            },
            "customer": {
                "id": 2,
                "name": "Petras",
                "email": "Petras123@gmail.com",
                "phoneNumber": "867296545"
            }
        },
        {
            "id": 3,
            "orderDate": "2019-03-04T20:12:20.207+0000",
            "completed": false,
            "game": {
                "id": 3,
                "name": "XCOM 2",
                "genre": "Strategy",
                "platform": "PC",
                "price": "49.99",
                "developer": "Dev3"
            },
            "customer": {
                "id": 3,
                "name": "Zilvinas",
                "email": "Zilve123@gmail.com",
                "phoneNumber": "869444455"
            }
        }
    ]
},
"_links": {
    "self": {
        "href": "http://localhost:8080/orders"
    }
}

}

同时,我只想提供指向它们的链接,例如 http://localhost:8080/game/1 http://localhost:8080/customer/1 用于第一个订单,但我不确定如何排除对象本身。我尝试使用@JsonView,但它只是响应并清空 Json 对象。

这是我的订单控制器

@RestController
public class OrderController {

    @Autowired
    private OrderService orderService;

    //@JsonView(View.Summary.class) // commented out because gives empty response
    @GetMapping("/orders")
    public ResponseEntity<Resources<Order>>getAllOrders(){

    List<Order> orders = orderService.getAllOrders();
    Resources<Order> resources = new Resources<Order>(orders);
    Link linkTo = 
linkTo(methodOn(this.getClass()).getAllOrders()).withSelfRel();
    resources.add(linkTo);
    return ResponseEntity.ok(resources);
    }

    @GetMapping("/orders/{orderId}")
    public Order getOrderById(@PathVariable int orderId) {
        return orderService.getOrderById(orderId);
    }
}

还有,我的 View 类

public class View {
    public interface Summary {}
}

另外,我现在没有使用任何数据库,并且所有对象实例都位于 CustomerService、OrderService、GameService 类的静态块中。

private static List <Order> orders = new ArrayList<Order>();
private static List <Game> games = new ArrayList<Game>();
private static List <Customer> customers = new ArrayList<Customer>();

static {
    GameService gameService = new GameService();
    CustomerService customerService = new CustomerService();
    games = gameService.getAllGames();
    customers = customerService.getAllCustomers();

    Order order1 = new Order(1,new Date(),false,games.get(0),customers.get(0));
    Order order2 = new Order(2,new Date(),false,games.get(1),customers.get(1));
    Order order3 = new Order(3,new Date(),false,games.get(2),customers.get(2));

    orders.add(order1);
    orders.add(order2);
    orders.add(order3);

}

最后,当向 GET 请求传递某种类型的参数时,我仍然希望它会显示所有信息(包括对象)

我现在被困了几天,没有其他想法。任何建议将不胜感激。

谢谢。

编辑

将 @JsonIgnore 添加到 getter 后,Game 和 Customer 不再出现在 Json 响应中。我仍然希望是否有人可以帮助我使用 JsonView 以及我需要采取哪些额外步骤才能不返回空对象“{}”(访问 /orders 时)。还更新了我的 OrderController。

【问题讨论】:

  • 看看this question。或使用 @JsonView 进行搜索。如何设置 ObjectMapper.writerWithView(..)?
  • @pirho 对不起,只是一个初学者,所以没有在任何地方设置 ObjectMapper。看了一下链接,我不确定我应该把它放在哪里以及如何使用它。我对 JsonView 所做的一切。是创建简单的 View 类,然后添加 JsonView。如您所见,在字段上方和控制器中。此外,JsonView。当我返回订单列表时工作正常,但是当我切换到资源和 ResponseEntity 现在它只返回一个“{}”作为响应。

标签: java json spring spring-boot


【解决方案1】:

在这种情况下,不要使用@JsonIgnore,只需创建一个单独的 DTO 并包含您想要的字段并在其中设置数据后返回。

【讨论】:

  • 谢谢。我使用了你建议的方法。
【解决方案2】:

使用@JsonIgnore 忽略响应中的对象

@JsonIgnore
private Game game;

@JsonIgnore
private Customer customer;

【讨论】:

  • 如果我以后想看到在链接中给出一些参数的对象怎么办?我读到预测是可能的。但它适用于 JsonIgnore 吗?
  • 另外,添加 JsonIgnore 并没有帮助。它仍然在响应中显示游戏和客户。
  • 没关系。当我将 JsonIgnore 添加到 getter 方法而不是字段本身时,它现在可以工作了。我仍然会等待 JsonView 的回复,也许我也会得到帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-05-03
  • 1970-01-01
  • 2012-08-31
  • 2014-12-28
  • 2019-12-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多