gpt4 book ai didi

java - Spring 支架 Controller

转载 作者:行者123 更新时间:2023-12-01 20:12:07 26 4
gpt4 key购买 nike

当结果是 array/list 时,我无法让 spring 序列化响应。因此,当我从 RestController 调用 clients 时,它确实返回 [{},{},{}],而不是真实对象,所有其他方法都可以正常工作。

package com.test.Domain.Client;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.util.UUID;

@Entity
@Table(name = "client")
public class Client {

@Column(name = "client_id")
@Id
private UUID clientId;
@Column(name = "name")
private String name;

private Client() {

}

private Client(UUID clientId, String name) {

this.clientId = clientId;
this.name = name;
}

public static Client create(String name)
{
return new Client(UUID.randomUUID(), name);
}
}
<小时/>
package com.test.Rest;

import com.test.Domain.Calendar.AppointmentRepository;
import com.test.Domain.Client.Client;
import com.test.Domain.Client.ClientRepository;
import com.test.Domain.Worker.WorkerRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

@org.springframework.web.bind.annotation.RestController
public class RestController {

@Autowired
private ClientRepository clientRepository;
@Autowired
private WorkerRepository workerRepository;
@Autowired
private AppointmentRepository appointmentRepository;


@RequestMapping(path = "/client", method = RequestMethod.POST)
public void registerClient(@RequestParam(name = "name") String name) {
this.clientRepository.save(Client.create(name));
}

@RequestMapping(path = "/clientCount", method = RequestMethod.GET)
public Long countClient() {
return this.clientRepository.count();
}

@RequestMapping(path = "/clients", method = RequestMethod.GET)
@ResponseBody
public List<Client> clients() {
List<Client> list = new ArrayList<Client>();
for (Client client : this.clientRepository.findAll()) {
list.add(client);
}

return list;
}
}

最佳答案

Jackson 需要 Getter 和 Setter 方法才能将 Client 对象正确序列化为 JSON。因此,返回一个空对象列表,并且缺少成员的值。将它们添加到 Client 中,响应应该看起来不错。

关于java - Spring 支架 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46531335/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com