java - 将 json 数组发送到 Rest 端点会导致 Jackson 解析异常

标签 java json spring-boot jackson

我用过的堆栈

  • Spring Boot 1.5.6 发布
  • ajax jquery 3.3.1

我的目标

我正在尝试将一些数据打印到jasper报告中,所以我创建了一个休息 Controller ,我想到从前端发送json数据并通过jackson api将其解析到pojo列表中,然后使用JRDataBean来处理我的报告

我的代码

当按下打印按钮时,我使用从 chrome 控制台获取的 ajax 发送这个 json 数组,方法是将其设为全局变量,然后使用副本(我在 google 上搜索到将变量内容作为字符串获取的 atrick)

  • 这是我的 json

.

   [ {
    "codeInterne": 45,
    "clientName": "TalcorpDZ",
    "clientPhone": "+213778217469",
    "codeExterne": "CLI201801",
    "email": "talcorpdz@gmail.com",
    "clientType": 0,
    "clientEtat": 1,
    "identifiant": "TalcorpDZ",
    "contacts": [
      {
        "nom": "Taleb",
        "prenom": "Mohammed Housseyn",
        "telephonePortable": "04330256699",
        "email": null
      }
    ],
    "adresses": [
      {
        "adress": "Batiments des enseignants Mohammed Khemisti",
        "ville": "Maghnia"
      }
    ]
  },
  {
    "codeInterne": 64,
    "clientName": "lkjhgf",
    "clientPhone": "+213778217469",
    "codeExterne": "dfghjk",
    "email": "talcorpdz@gmail.com",
    "clientType": 1,
    "clientEtat": 1,
    "identifiant": "lkjhgf",
    "contacts": [
      {
        "nom": "Taleb",
        "prenom": "Mohammed",
        "telephonePortable": "02354649",
        "email": "talcorpdz@gmail.com"
      }
    ],
    "adresses": [
      {
        "adress": "Batiments des enseignants Mohammed Khemist",
        "ville": "Maghnia"
      }
    ]
  }
]
  • 这是我执行发布请求的部分

.

$(document).on('click', '#menu0-func1-menu0-func1', function(){
        console.log(printData);
            var settings = {
                "async" : true,
                "crossDomain" : true,
                "url" : "http://"+document.location.host+"/facturation/print/client",
                "method" : "POST",
                "headers" : {
                    "cache-control" : "no-cache",
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                "processData" : false,
                "contentType" : "application/json",
                "dataType" : "json",
                "data" : printData
            }

            $.ajax(settings).done(function(response) {
                console.log(response);

            });
    });

该帖子受到我的 Controller 的好评,其编码如下:

@RestController
@RequestMapping(PrintController.API)
public class PrintController {
    public static final String API="print";


    @PostMapping("client")
    public void export(@RequestBody List<ClientJsonDto> datas,HttpServletResponse response){

        System.out.println(datas);

        // processing the print mechanisme

    }
}

最后这是我的 ClientJsonDto.java

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
    "codeInterne",
    "clientName",
    "clientPhone",
    "codeExterne",
    "email",
    "clientType",
    "clientEtat",
    "identifiant",
    "contacts",
    "adresses"
})
public class ClientJsonDto {

    @JsonProperty("codeInterne")
    private Integer codeInterne;
    @JsonProperty("clientName")
    private String clientName;
    @JsonProperty("clientPhone")
    private String clientPhone;
    @JsonProperty("codeExterne")
    private String codeExterne;
    @JsonProperty("email")
    private String email;
    @JsonProperty("clientType")
    private Integer clientType;
    @JsonProperty("clientEtat")
    private Integer clientEtat;
    @JsonProperty("identifiant")
    private String identifiant;
    @JsonProperty("contacts")
    private List<Contact> contacts = null;
    @JsonProperty("adresses")
    private List<Adress> adresses = null;
    @JsonIgnore
    private Map<String, Object> additionalProperties = new HashMap<String, Object>();

// getters, setters 
}

地址.java

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
    "adress",
    "ville"
})
public class Adress {

    @JsonProperty("adress")
    private String adress;
    @JsonProperty("ville")
    private String ville;
    @JsonIgnore
    private Map<String, Object> additionalProperties = new HashMap<String, Object>();

//getters, setters
}

contact.java

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
    "nom",
    "prenom",
    "telephonePortable",
    "email"
})
public class Contact {

    @JsonProperty("nom")
    private String nom;
    @JsonProperty("prenom")
    private String prenom;
    @JsonProperty("telephonePortable")
    private String telephonePortable;
    @JsonProperty("email")
    private String email;
    @JsonIgnore
    private Map<String, Object> additionalProperties = new HashMap<String, Object>();
 //getters setters
}

我面临的异常(exception)是:

2018-11-18 15:12:40.255 WARN 1768 --- [nio-8082-exec-9] .w.s.m.s.DefaultHandlerExceptionResolver : Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Unrecognized token 'object': was expecting ('true', 'false' or 'null'); nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'object': was expecting ('true', 'false' or 'null') at [Source: java.io.PushbackInputStream@1df244f9; line: 1, column: 9]

在 Jackson 尝试编码之前,我可以做什么来查看我的其余 Controller 作为请求主体接收到的内容?

我该如何解决这个异常?

最佳答案

您的 json 值和映射都是正确的,但我看不到具有后映射请求的生产者和消费者,因为您必须显式定义生产者和消费者。

该错误可能是由于您提供给 Controller 的数据格式造成的。您的 Controller 方法需要 JSON 字符串。例如,对于 jQuery,JSON.stringify() 会为您提供 JSON 字符串。因此,我建议您在将数据发送到该 Controller 的客户端确认这一点。

您需要更改和检查的代码。

@RestController
@RequestMapping(PrintController.API)
public class PrintController {
    public static final String API="print";

@PostMapping("client",produces=MediaType.APPLICATION_JSON_VALUE,consumes=MediaType.APPLICATION_JSON_VALUE)
        public void export(@RequestBody List<ClientJsonDto> datas,HttpServletResponse response){

            System.out.println(datas);

            // processing the print mechanisme

        }
    }

关于java - 将 json 数组发送到 Rest 端点会导致 Jackson 解析异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53362658/

相关文章:

java - Firebase - 按(孙) child 的存在进行查询

jquery - 为什么这里不需要 JSONP ?

json - 为嵌套的json数据创建Hive表

java - Hibernate完整性约束冲突: NOT NULL check constraint: For onetoOne Mapping using spring boot crud

mongodb - 如何配置 MongoRepository 以使用新的 MongoClient API?

java - 如何使用 Selenium 和 POI 从 Excel 的第一行迭代并尝试登录,然后再次迭代到第二行并尝试再次登录?

java - 为什么在使用 instanceof 时子类和父类(super class)都为真?

java - 正确使用 LabelValueBean

javascript - 显示 JSON 数据的下载进度百分比

RestTemplate--> Exchange 产生 : 422 Unprocessable Entity