【问题标题】:JSON POST Request getting exception on server sideJSON POST请求在服务器端获取异常
【发布时间】:2018-01-13 01:51:03
【问题描述】:

我正在尝试设置基于 Spring JPA 的 REST API。我正在使用 com.fasterxml.jackson.core 处理 JSON 请求和响应。在我的控制器中,我有一个发布请求,我基本上在其中执行创建操作。以下是执行此操作的代码:

@Autowired
    CustomerRepository repository;

    @RequestMapping(value = "/postcustomer", method = RequestMethod.POST)
    public void postCustomer(@RequestBody Customer customer) {

        repository.save(new Customer(customer.getFirstName(), customer.getLastName()));
    }

如您所见,我需要在我的身体中发送一个客户类型的对象。我正在尝试使用邮递员对其进行测试,以下是我发送到服务器的 JSON:

{
    "status": "Done",
    "data": [
        "Customer" : {
            "firstname" : "test",
            "lastname" : "123"
        }
    ]
}

我是否发送了错误的请求?因为我不断收到一个异常说:

{
"timestamp":1501908753094,
"status":400,
"error":"Bad Request",
"exception":"org.springframework.http.converter.HttpMessageNotReadableException",
"message":"JSON parse error: Unexpected character (':' (code 58)): was expecting comma to separate Array entries; nested exception is com.fasterxml.jackson.core.JsonParseException: Unexpected character (':' (code 58)): was expecting comma to separate Array entries\n at [Source: java.io.PushbackInputStream@6f57265c; line: 4, column: 18]",
"path":"/uzmi/postcustomer"
}

更新: 根据答案更改我的解决方案后,我有这个: CustomerCOntroller.java:

import com.test.message.Response;
import com.test.repo.CustomerRepository;    
@RestController
public class CustomerController {    
    @Autowired
    CustomerRepository repository;    
    @RequestMapping(value = "/postcustomer", method = RequestMethod.POST)
    public void postCustomer(@RequestBody Response request) {
        request.getData().forEach((data) -> {
            repository.save(data.getCustomer());
        });
    }    
}

Response.java:

package com.test.message;    
import java.io.Serializable;
import java.util.List;    
public class Response implements Serializable {    
    private String status;    
    private List<Data> data;    
    public Response(String status, List<Data> data) {
        this.status = status;
        this.data = data;
    }    
    public Response() {
    }    
    public String getStatus() {
        return status;
    }    
    public void setStatus(String status) {
        this.status = status;
    }    
    public List<Data> getData() {
        return data;
    }    
    public void setData(List<Data> data) {
        this.data = data;
    }    
}

Data.java:

package com.test.message;    
import com.fasterxml.jackson.annotation.JsonProperty;
import com.test.model.Customer;    
public class Data {    
    @JsonProperty("Customer")
    private Customer customer;    
    public Customer getCustomer() {
        return customer;
    }    
    public void setCustomer(Customer customer) {
        this.customer = customer;
    }
    public Data() {
    }
    public Data(Customer customer) {
        this.customer = customer;
    }
}

但现在当我使用以下 JSON 尝试 postcontroller api 时:

{
    "status": "Done",
    "data": [ {
        "Customer": {
            "firstname" : "test",
            "lastname" : "123"
        }
    }]
}

我收到以下错误:

{
    "timestamp": 1502014916458,
    "status": 400,
    "error": "Bad Request",
    "exception": "org.springframework.http.converter.HttpMessageNotReadableException",
    "message": "JSON parse error: Can not construct instance of com.test.message.Response: no suitable constructor found, can not deserialize from Object value (missing default constructor or creator, or perhaps need to add/enable type information?); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of com.test.message.Response: no suitable constructor found, can not deserialize from Object value (missing default constructor or creator, or perhaps need to add/enable type information?)\n at [Source: java.io.PushbackInputStream@157f2538; line: 2, column: 5]",
    "path": "/test/postcustomer"
}

更新 2: customer.java:

package com.test.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "customer")
public class Customer implements Serializable {
    private static final long serialVersionUID = -3009157732242241606L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;
    @Column(name = "firstname")
    private String firstName;
    @Column(name = "lastname")
    private String lastName;
    protected Customer() {
    }
    public long getId() {
        return id;
    }
    public void setId(long id) {
        this.id = id;
    }
    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public Customer(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }
}

任何想法我哪里出错了?

【问题讨论】:

  • @sunkuet02 它确实有帮助,但我没有完全解决问题。你能检查我更新的问题吗?
  • 在Data 类中添加两个构造函数。一个参数为Customer 类型,另一个为空。另外,在Data 类中实现Serializable,然后知道结果。
  • 你更新你的Data类了吗?有构造函数?
  • 你在json里给了firstname,但是变量名是firstName。这就是不匹配。您可以更改变量名称。更好的是,您可以在 firstName 变量上方添加 @JsonProperty("firstname")。同样姓氏。它会起作用的。
  • @sunkuet02 jsonproperty 解决方案有效!谢谢!

标签: json spring spring-data-jpa


【解决方案1】:

首先,您给定的 json 格式不正确。我已更改为以下格式。

{
    "status": "Done",
    "data": [ {
        "Customer": {
            "firstname" : "test",
            "lastname" : "123"
        }
    }]
}

如果你想接受上面的json作为请求体,那么你需要再添加两个类并分别更改控制器。

更改控制器方法

@RequestMapping(value = "/postcustomer", method = RequestMethod.POST)
public void postCustomer(@RequestBody PostCustomerRequest request) {
    for(Data data : request.getData()) {
        repository.save(data.getCustomer());
    }
}

显然,您需要 PostCustomerRequest 和 Data 类。

PostCustomerRequest 类

public class PostCustomerRequest implements Serializable {
    private String status;

    private List<Data> data;

    // Respective constructor, getter and setter methods
}

数据类

public class Data {
    @JsonProperty("Customer")
    private Customer customer;

    // Respective constructor, getter and setter methods
}

那你就可以在json上面发你了。

注意

在这里,您可以很容易地注意到,Data 类如果不包装 Customer 就没有用处。你可以放弃它。这也最小化了您的json 格式。如果您不想使用Data 类,则在PostCustomerRequest 中使用List&lt;Customer&gt;。如果是这样,那么你 json 将被最小化为

{
    "status": "Done",
    "data": [ 
        {
            "firstname" : "test",
            "lastname" : "123"
        }
    ]
}

而且我想每个人都会建议这种格式。

最后更新

你在json中给了firstname,但是变量名是firstName。这就是不匹配。您可以更改变量名称。更好的是,您可以在 firstName 变量上方添加 @JsonProperty("firstname")。同样为姓氏做。它会起作用的。

还有一件事是,您可以在线将您的json 转换为POJO。有好几个,但我用过JSON Schema to POJO。

【讨论】:

    【解决方案2】:

    您不需要将status , data 发送到json 中,您可以只将json 正文发送到请求中,RequestBody 可以将其属性与实体或pojo 映射。您只能将参数和值发送到 JSON boby,您可以在下面找到它:

        {
            "firstname" : "test",
            "lastname" : "123"
        }
    

    【讨论】:

    • 我可以这样做,但我想坚持使用状态和数据的方法。如何在数据字段中打包对象?
    猜你喜欢
    • 2017-05-21
    • 2023-03-30
    • 1970-01-01
    • 2020-09-26
    • 2011-06-01
    • 2017-10-18
    • 1970-01-01
    • 2017-06-08
    • 1970-01-01
    相关资源
    最近更新 更多