2014-01-12 2 views
2

다음은 간단한 Spring MVC REST 예제이다. PUT 요청에, 나는 다음과 같은 예외 점점 오전 : 게터와Spring MVC REST Json 변환 예외

@RequestMapping(method = RequestMethod.PUT, value = "/{id}") 
public ResponseEntity<Property> updateProperty(@RequestBody Property property, 
               @PathVariable String id) { 
    final ResponseEntity<Property> response = 
      new ResponseEntity<Property>(property, HttpStatus.OK); 
    return response; 
} 

Property는 표준 POJO/:

org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON: Unrecognized field "property" (Class domain.Property), not marked as ignorable 
    at [Source: [email protected]; line: 1, column: 14] (through reference chain: domain.Property["property"]); 
nested exception is org.codehaus.jackson.map.exc.UnrecognizedPropertyException:        
    Unrecognized field "property" (Class domain.Property), not marked as ignorable 
    at [Source: [email protected]; line: 1, column: 14] (through reference chain: domain.Property["property"]) 

나는 다음 JSON을

{"property": 
    { 
     "name":"name", 
     "age":"22" 
    } 
} 

에 따라 수신하고 나의 REST 방식입니다 이름과 나이를 세터.

어떻게이 예외를 해결할 수 있습니까?

+0

"Property"클래스 코드도 올리십시오. –

+1

JSON에 "속성"값이 있고 속성에 "이름"과 "나이"만 들어 있습니다. JSON에서 속성을 제거해야합니다. '{ "name": "name", "age": "22"}' –

답변

2

에는 이라는 속성이 있으며 Property 클래스의 property 필드로 매핑 할 수 없습니다. JSON을 변경하여이 필드를 생략하십시오. JSON을 변경하여 property 속성을 제거 할 수없는 경우 Property 클래스의 래퍼를 만듭니다.

class PropertyWrapper(){ 

    private Property property; 

    public Property getProperty(){ 
     return property; 
    } 

    public Property setProperty(Property p){ 
     this.property = property; 
    } 
} 

그런 다음 컨트롤러 내에서 PropertyWrapper를 사용

public ResponseEntity<Property> updateProperty(@RequestBody PropertyWrapper property, 
               @PathVariable String id) { 
    final ResponseEntity<Property> response = 
      new ResponseEntity<Property>(property.getProperty(), HttpStatus.OK); 
    return response; 
} 
6

귀하의 JSON은

{"property": { "name":"name", "age":"22" } } 그래서 필드에 대 한 검색 JSON 파서가 Property 클래스에 property(setProperty() method exactly)라는 포함되어 있습니다. 따라서 Property 클래스에 getter 및 setter가 포함 된 property 필드가 있어야합니다.

그래서 수업 시간에하지 않은 JSON으로 파싱하는 모든 필드를 무시, 당신은

@JsonIgnoreProperties(ignoreUnknown = true) 
public class Property 

는 그래서 모든 필드를 무시 될 것이다 클래스에서 @JsonIgnoreProperties(ignoreUnknown = true)

을 가지는 클래스를 주석해야 귀하의 속성 클래스에 JSON 문자열이 없습니다.

하지만 여전히 문제는 해결되지 않습니다. JSON 문자열 name and age속성 안에 있습니다. 그래서 JSON 파서는 기본적으로 property (클래스의 객체)이라는 필드를 찾을 것입니다. 그리고 나서 객체 내부에서 이름과 나이 값을 설정합니다. 그렇다면 JSON ignore 속성을 설정할 필요가 없습니다. 당신의 컨트롤러에서 getter 및 setter 다음

public class Property{ 
    private Property property; 
    private String name; 
    private int age; 
    //getter and setter 
} 

와 함께 재산권 클래스 내부 property라고

는 그래서 부동산의 한 객체를 생성 세 가지 옵션

1을 한 등급

public ResponseEntity<Property> updateProperty(@RequestBody Property property, 
               @PathVariable String id) { 

    Property property2=new Property(); 
    property2=property.getProperty(); 

    //Get Strings from normal object property2 

    String name = property2.getName(); 
    int age = property2,getAge(); 


    final ResponseEntity<Property> response = 
      new ResponseEntity<Property>(property, HttpStatus.OK); 
    return response; 
} 

.혼동을 피하기 위해 속성이 인 필드를 Property으로 사용하여 다른 클래스를 만듭니다.

예 :

public class PropertiesJson{ 
private Property property 
//getter and setter 
} 

이어서 제어기 대신

3 속성

public ResponseEntity<Property> updateProperty(@RequestBody PropertiesJson propertiesJson, 
                @PathVariable String id) { 

     Property property=propertiesJson.getProperty(); 

     //Get Strings from normal object property 

     String name = property.getName(); 
     int age = property.getAge(); 


     final ResponseEntity<Property> response = 
       new ResponseEntity<Property>(property, HttpStatus.OK); 
     return response; 
    } 
의 사용. 다른 옵션은 JSON 문자열을 변경하는 것입니다.

{ "name":"name", "age":"22" } 

충분합니다. JSON 문자열을 변경할 수 있다면 더 좋은 생각입니다. 그렇지 않으면 다른 옵션을 선택해야합니다.

+0

감사합니다. Shiju. 귀하의 대답도 정확합니다. 나는 더 명확한 분리 때문에 대답으로 케빈 답장을 표시했다. – amique

관련 문제