在本文中,我们将带你了解RESTPOST控制器说:无法读取JSON:由于输入结束,没有要映射的内容在这篇文章中,我们将为您详细介绍RESTPOST控制器说:无法读取JSON:由于输入结束,没有要映射的
在本文中,我们将带你了解REST POST控制器说:无法读取JSON:由于输入结束,没有要映射的内容在这篇文章中,我们将为您详细介绍REST POST控制器说:无法读取JSON:由于输入结束,没有要映射的内容的方方面面,并解答无法读取actors.json常见的疑惑,同时我们还将给您一些技巧,以帮助您实现更有效的asp.net-mvc – 控制器操作无法从JSON读取Guid POST、domain-name-system – 绑定:由于NS的“意外输入结束”、Jackson Mapper没有反序列化JSON – (无法读取JSON:已经有了id(java.lang.Integer)的POJO)、java – com.fasterxml.jackson.databind.JsonMappingException:由于输入结束没有要映射的内容。
本文目录一览:- REST POST控制器说:无法读取JSON:由于输入结束,没有要映射的内容(无法读取actors.json)
- asp.net-mvc – 控制器操作无法从JSON读取Guid POST
- domain-name-system – 绑定:由于NS的“意外输入结束”
- Jackson Mapper没有反序列化JSON – (无法读取JSON:已经有了id(java.lang.Integer)的POJO)
- java – com.fasterxml.jackson.databind.JsonMappingException:由于输入结束没有要映射的内容
REST POST控制器说:无法读取JSON:由于输入结束,没有要映射的内容(无法读取actors.json)
我正在针对REST控制器POST处理程序进行集成测试。好吧,我正在努力。
它给我HttpMessageNotReadableException异常:无法读取JSON:由于输入结束,没有内容要映射
这是我的控制器:
@Controller@RequestMapping("admin")public class AdminController { private static Logger logger = LoggerFactory.getLogger(AdminController.class); private static final String TEMPLATE = "Hello, %s!"; @Autowired private AdminService adminService; @Autowired private AdminRepository adminRepository; @RequestMapping(value = "crud", method = RequestMethod.POST, produces = "application/json; charset=utf-8") @ResponseBody public ResponseEntity<Admin> add(@RequestBody Admin admin, UriComponentsBuilder builder) { AdminCreatedEvent adminCreatedEvent = adminService.add(new CreateAdminEvent(admin.toEventAdmin())); Admin createdAdmin = Admin.fromEventAdmin(adminCreatedEvent.getEventAdmin()); HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.add("Content-Type", "application/json; charset=utf-8"); responseHeaders.setLocation(builder.path("/admin/{id}").buildAndExpand(adminCreatedEvent.getAdminId()).toUri()); return new ResponseEntity<Admin>(createdAdmin, responseHeaders, HttpStatus.CREATED); } @ExceptionHandler(HttpMessageNotReadableException.class) @ResponseBody public String handleException(HttpMessageNotReadableException e) { return e.getMessage(); }}
基本测试类:
@RunWith(SpringJUnit4ClassRunner.class)@WebAppConfiguration@ContextConfiguration( classes = { ApplicationConfiguration.class, WebSecurityConfig.class, WebConfiguration.class, WebTestConfiguration.class })@Transactionalpublic abstract class AbstractControllerTest { @Autowired private WebApplicationContext webApplicationContext; @Autowired private FilterChainProxy springSecurityFilterChain; protected MockHttpSession session; protected MockHttpServletRequest request; protected MockMvc mockMvc; @Before public void setup() { this.mockMvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext).addFilters(this.springSecurityFilterChain).build(); }}
集成测试:
@Testpublic void testAdd() throws Exception { HttpHeaders httpHeaders = Common.createAuthenticationHeaders("stephane" + ":" + "mypassword"); this.mockMvc.perform( post("/admin/crud").headers(httpHeaders) .param("firstname", "Stephane") .param("lastname", "Eybert") .param("login", "stephane") .param("password", "toto") ).andDo(print()) .andExpect( status().isOk() ).andReturn();}
控制台日志必须说些什么:
2013-11-04 19:31:23,168 DEBUG [HttpSessionSecurityContextRepository] SecurityContext stored to HttpSession: ''org.springframework.security.core.context.SecurityContextImpl@158ddda0: Authentication: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@158ddda0: Principal: org.springframework.security.core.userdetails.User@552e813c: Username: stephane; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_ADMIN; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@957e: RemoteIpAddress: 127.0.0.1; SessionId: null; Granted Authorities: ROLE_ADMIN''2013-11-04 19:31:23,168 DEBUG [RequestResponseBodyMethodProcessor] Written [Could not read JSON: No content to map due to end-of-input at [Source: UNKNOWN; line: 1, column: 1]; nested exception is com.fasterxml.jackson.databind.JsonMappingException: No content to map due to end-of-input at [Source: UNKNOWN; line: 1, column: 1]] as "application/json;charset=utf-8" using [org.springframework.http.converter.StringHttpMessageConverter@10d328]2013-11-04 19:31:23,169 DEBUG [TestDispatcherServlet] Null ModelAndView returned to DispatcherServlet with name '''': assuming HandlerAdapter completed request handling2013-11-04 19:31:23,169 DEBUG [TestDispatcherServlet] Successfully completed request2013-11-04 19:31:23,169 DEBUG [ExceptionTranslationFilter] Chain processed normally2013-11-04 19:31:23,169 DEBUG [SecurityContextPersistenceFilter] SecurityContextHolder now cleared, as request processing completedMockHttpServletRequest: HTTP Method = POST Request URI = /admin/crud Parameters = {firstname=[Stephane], lastname=[Eybert], login=[stephane], password=[toto]} Headers = {Content-Type=[application/json], Accept=[application/json], Authorization=[Basic c3RlcGhhbmU6bXlwYXNzd29yZA==]} Handler: Type = com.thalasoft.learnintouch.rest.controller.AdminController Method = public org.springframework.http.ResponseEntity<com.thalasoft.learnintouch.rest.domain.Admin> com.thalasoft.learnintouch.rest.controller.AdminController.add(com.thalasoft.learnintouch.rest.domain.Admin,org.springframework.web.util.UriComponentsBuilder) Async: Was async started = false Async result = null Resolved Exception: Type = org.springframework.http.converter.HttpMessageNotReadableException ModelAndView: View name = null View = null Model = null FlashMap:MockHttpServletResponse: Status = 200 Error message = null Headers = {Content-Type=[application/json;charset=utf-8], Content-Length=[254]} Content type = application/json;charset=utf-8 Body = Could not read JSON: No content to map due to end-of-input at [Source: UNKNOWN; line: 1, column: 1]; nested exception is com.fasterxml.jackson.databind.JsonMappingException: No content to map due to end-of-input at [Source: UNKNOWN; line: 1, column: 1] Forwarded URL = null Redirected URL = null Cookies = []2013-11-04 19:31:23,177 DEBUG [TransactionalTestExecutionListener] No method-level @Rollback override: using default rollback [true] for test context [TestContext@ce4625 testClass = AdminControllerTest, testInstance = com.thalasoft.learnintouch.rest.AdminControllerTest@1b62fcd, testMethod = testAdd@AdminControllerTest, testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@9be79a testClass = AdminControllerTest, locations = ''{}'', classes = ''{class com.thalasoft.learnintouch.rest.config.ApplicationConfiguration, class com.thalasoft.learnintouch.rest.config.WebSecurityConfig, class com.thalasoft.learnintouch.rest.config.WebConfiguration, class com.thalasoft.learnintouch.rest.config.WebTestConfiguration}'', contextInitializerClasses = ''[]'', activeProfiles = ''{}'', resourceBasePath = ''src/main/webapp'', contextLoader = ''org.springframework.test.context.web.WebDelegatingSmartContextLoader'', parent = [null]]]
有什么线索吗?
答案1
小编典典我将.param()方法替换为.content()方法之一:
post("/admin/crud").headers(httpHeaders) .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON) .content("{ \"firstname\" : \"" + admin0.getFirstname() + "\", \"lastname\" : \"" + admin0.getLastname() + "\", \"email\" : \"" + admin0.getEmail() + "\", \"login\" : \"" + admin0.getLogin() + "\", \"password\" : \"" + admin0.getPassword() + "\", \"passwordSalt\" : \"" + admin0.getPasswordSalt() + "\" }") ).andDo(print()) .andExpect(status().isCreated()) .andExpect(jsonPath("$.firstname").value(admin0.getFirstname())) .andExpect(jsonPath("$.lastname").value(admin0.getLastname())) .andExpect(jsonPath("$.email").value(admin0.getEmail())) .andExpect(jsonPath("$.login").value(admin0.getLogin())) .andExpect(jsonPath("$.password").value(admin0.getPassword())) .andExpect(jsonPath("$.passwordSalt").value(admin0.getPasswordSalt())) .andReturn();
现在,它可以按预期工作。
asp.net-mvc – 控制器操作无法从JSON读取Guid POST
[Route("api/person")] [HttpPost] public async Task<IActionResult> Person([FromBody] Guid id) { ... }
我发帖到它:
POST /api/person HTTP/1.1 Host: localhost:5000 Content-Type: application/json Cache-Control: no-cache Postman-Token: 747a5d76-398c-e1c7-b948-b276bb24976c { "id": "b85f75d8-e6f1-405d-90f4-530af8e060d5" }
我的动作被击中,但它收到的Guid总是一个Guid.Empty值(即:它没有得到我传递的值).
请注意,如果我使用url参数而不是[FromBody],这可以正常工作,但我想使用http帖子的主体.
解决方法
By default,Web API uses the following rules to bind parameters:
- If the parameter is a “simple” type,Web API tries to get the value from the URI. Simple types include the .NET primitive types (int,
bool,double,and so forth),plus TimeSpan,DateTime,Guid,decimal,
and string,plus any type with a type converter that can convert from
a string. (More about type converters later.)- For complex types,Web API tries to read the value from the message body,using a media-type formatter.
此外,在使用[FromBody]部分的同一篇文章中,您可以看到可以在参数上添加属性[FromBody]的示例,以便绑定请求正文中的值,就像您一样.但是这里是catch – 示例显示,在这种情况下,请求主体应该包含原始值,而不是JSON对象.
所以在你的情况下你有两个选择:
第一个选项是更改您的请求以提供原始值而不是JSON对象
POST /api/person HTTP/1.1 Host: localhost:5000 Content-Type: application/json Cache-Control: no-cache Postman-Token: 747a5d76-398c-e1c7-b948-b276bb24976c "b85f75d8-e6f1-405d-90f4-530af8e060d5"
第二个选项是提供具有单个属性的复杂对象并将其用作参数:
public class Request { public Guid Id { get; set; } } [Route("api/person")] [HttpPost] public async Task<IActionResult> Person([FromBody] Request request) { ... }
domain-name-system – 绑定:由于NS的“意外输入结束”
该区域在主站上工作正常,但在奴隶上我遇到了这些错误:
21-May-2014 19:06:07.573 general: info: zone example.com/IN: refresh: failure trying master 1.2.3.4#53 (source 0.0.0.0#0): unexpected end of input
这是我的绑定文件的样子:
@ IN SOA ns1.example.com. admin.example.com. ( 2014052116 ; Serial 28800 ; Refresh 180 ; Retry 604800 ; Expire 21600 ) ; Minimum 86400 IN A 1.2.3.4 86400 IN MX 10 mail.example.com. 86400 IN MX 20 mail2.example.com. 86400 IN NS ns1.example.com. 86400 IN NS ns2.example.com. 86400 IN NS ns3.example.com. 86400 IN NS ns1.example.net. 86400 IN NS ns2.example.net. 86400 IN NS ns3.example.net. 86400 IN NS ns1.example.org. ; until here it works -- if I uncomment the below here,I'll get "end of input" failures. ; 86400 IN NS ns2.example.org. ; 86400 IN NS ns3.example.org. * 86400 IN A 1.2.3.4 [...]
如果我取消注释被注释的两条NS线 – 我将得到“输入结束”错误.如果我让他们评论,一切正常.
是否存在导致其崩溃的最大NS或文件大小?
谢谢.
编辑:
命名checkzone:
master # named-checkzone example.com example.com. zone example.com/IN: example.com/MX 'mail.example.com' is a CNAME (illegal) zone example.com/IN: example.com/MX 'mail2.example.com' is a CNAME (illegal) zone example.com/IN: loaded serial 2014052105 OK
全球选择:
options { directory "/var/cache/bind"; auth-nxdomain no; # conform to RFC1035 listen-on-v6 { any; }; listen-on { any; }; dnssec-enable yes; recursion no; statistics-file "/var/log/named.stats"; try-tcp-refresh yes; };
版本(在所有三台服务器上都相同):
# named -v BIND 9.8.4-rpz2+rl005.12-P1
解决方法
您遇到的问题是SOA响应将包含的不仅仅是QUESTION和ANSWER部分:
> AUTHORITY部分将包含所有已配置的名称服务器.
> ADDITIONAL部分将包含这些名称服务器的所有已知A和AAAA记录.
这就是调整NS记录或其关联的A / AAAA记录对整个区域传输成功产生影响的原因,但添加其他记录类型没有影响.您的组合权限数据对于可以通过UDP传输的数据来说太大了.
不幸的是,我不知道有任何解决方法. BIND管理员参考手册确实引用了try-tcp-refresh选项,但是默认为yes,并且在选项中没有禁用它.我不确定区域转移是你问题的结束.即使它成功了,这也会给任何客户带来问题,而这些客户反过来会提出包含你的AUTHORITY和ADDITIONAL部分的任何请求. ednS0旨在解决这样的问题,但我认为AUTHORITY膨胀在功能上太低,无法启动.
希望我的分析在某种程度上是错误的.我认为你有一个非常有趣的问题,我希望看到有人为此提供更好的答案,因为我也可以从中学习.
Jackson Mapper没有反序列化JSON – (无法读取JSON:已经有了id(java.lang.Integer)的POJO)
在将json发布到Spring Controller时获得上述异常.看来Jackson Mapper无法反序列化json. CategoryDTO注释为:
@JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class,property="@id",scope = CategoryDTO.class)
JSON:
[
{
"categories":[
{
"@id":27048,"name":"Sportbeha's","description":null,"parent":{
"@id":22416,"name":"fitness","parent":{
"@id":21727,"name":"Collectie","description":null
}
}
},{
"@id":27050,"parent":{
"@id":24474,"name":"Voetbal","parent":21727
}
}
]
},{
"categories":[
{
"@id":27048,"parent":21727
}
}
]
}
]
Java代码:
@JsonSerialize(include= JsonSerialize.Inclusion.NON_NULL)
@JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class,scope = CategoryDTO.class)
@JsonIgnoreProperties(ignoreUnkNown = true)
public class CategoryDTO implements Serializable{
private Long id;
private String name;
private String description;
private CategoryDTO parent;
@JsonIgnore
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public CategoryDTO getParent() {
return parent;
}
public void setParent(CategoryDTO parent) {
this.parent = parent;
}
}
**Spring Controller :**
@RequestMapping(value = "/categories",method = RequestMethod.POST,consumes = "application/json;charset=UTF-8",produces = "application/json;charset=UTF-8")
public ResponseEntity
问题似乎与这片json有关:
"parent":{
"@id":21727,"description":null
}
它存在于数组中的两个对象中.
最佳答案
如果对每个嵌套对象使用相同的CategoryDto,
"parent": 21727
因为杰克逊期待一个对象,所以不会反序列化.要仅使用id反序列化父CategoryDto,您需要POST以下JSON:
"parent": {
"@id": 21727
}
java – com.fasterxml.jackson.databind.JsonMappingException:由于输入结束没有要映射的内容
我写了这样的代码:
// execute the client with get method InputStream inputStream = getmethod.getResponseBodyAsstream(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); ObjectMapper objectMapper = new ObjectMapper(); JsonFactory jsonFactory = new JsonFactory(); List<OwnerDetail> owners = new ArrayList<>(); JsonParser jsonParser = jsonFactory.createJsonParser(inputStream); if (jsonParser.nextToken() != null && jsonParser.) { // end-of-input owners = objectMapper.readValue(bufferedReader,TypeFactory.defaultInstance().constructCollectionType(List.class,OwnerDetail.class)); }
以上块给出了以下错误:
com.fasterxml.jackson.databind.JsonMappingException: No content to map due to end-of-input at [Source: java.io.BufferedReader@5e66c5fc; line: 1,column: 1] at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:164) at com.fasterxml.jackson.databind.ObjectMapper._initForReading(ObjectMapper.java:3029) at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:2971) at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2128)
任何帮助,将不胜感激.谢谢.
解决方法
如果您的代码是拦截器,您可以尝试再次创建响应并返回如下:
Request request = chain.request(); Response originalResponse = chain.proceed(request); final ResponseBody original = originalResponse.body(); // if(request.url().toString().equalsIgnoreCase(string)){ if (originalResponse.code() == HttpURLConnection.HTTP_OK) { try { String response = originalResponse.body().string(); JSONObject mainObject = new JSONObject(response); // your mapping - manipulation code here. originalResponse = originalResponse.newBuilder() .header("Cache-Control","max-age=60") .body(ResponseBody.create(original.contentType(),mainObject.toString().getBytes())) .build(); } catch (JSONException | IOException e) { e.printstacktrace(); } } return originalResponse;
这里再次创建响应并返回.
请告诉我任何更新.
关于REST POST控制器说:无法读取JSON:由于输入结束,没有要映射的内容和无法读取actors.json的介绍现已完结,谢谢您的耐心阅读,如果想了解更多关于asp.net-mvc – 控制器操作无法从JSON读取Guid POST、domain-name-system – 绑定:由于NS的“意外输入结束”、Jackson Mapper没有反序列化JSON – (无法读取JSON:已经有了id(java.lang.Integer)的POJO)、java – com.fasterxml.jackson.databind.JsonMappingException:由于输入结束没有要映射的内容的相关知识,请在本站寻找。
本文标签: