2016-07-12 3 views
1

컨트롤러에 JSON으로 전달하는 동적 이름/값 쌍이 있습니다.AJAX 게시 동적 JSON 개체 MVC 매핑

예 : 동적 JSON은 개체

{"vehicles":[{"odometer_675552753":"73750","odometer_723646452":"68127""price_709725300":"22984","price_709725299":"22999"}]} 


var vehicleData = { 
     vehicles : [] 
    }; 

var vehicles = {}; 
$('.firDataField').each(function() { 
    var id = $(this).attr("name"); 
    var value = $(this).val(); 
    vehicles[id]=value; 
}); 
vehicleData.vehicles.push(vehicles); 

$.ajax({ 
    url: 'SaveVehicles.html', 
    contentType : 'application/json; charset=utf-8', 
    data:JSON.stringify(vehicleData), 
    type: "POST", 
    cache:false, 
    dataType : 'json', 
    success: function(data){   
     hideAjaxLoader(); 
    }, 
    error : function(jqxhr, textStatus, errorThrown) { 
     $('tbody#tbodyVehicleSearchData').html(''); 
     hideLoading(); 
     showGenericErrorMessage(jqxhr, textStatus, errorThrown, "VehicleSearch"); 
    } 
}); 


Controller: 

@RequestMapping("/SaveVehicles.html") 
public void 
String saveVehicles(
     @RequestParam(required = false, value = "vehicles") String jsonVehicleObject, 
     HttpServletRequest request, Model model) 
     throws Exception{ 
    LOGGER.entry(); 

    System.out.println("json: " + jsonVehicleObject); 
} 

jsonVehicleObject는 항상 null의 JQuery와

이하로 사용하여 생성. RequestBody를 Vehicle과 함께 객체 유형으로 사용해 보았습니다. 그러나 사용하지 마십시오. 어떤 제안?

답변

0

AJAX에서 type: 'Post'을 사용하는 경우 컨트롤러에 요청 유형을 추가해야한다는 의미입니다. 컨트롤러에이를 사용하여

시도,

[HttpPost] 
public void 
String saveVehicles(..) 

방법에서 사용 httpPost하는 응답의 유형을 정의합니다.

0

잭슨을 사용합니다. 잭슨 JSON에서 /로 JSON 변환

당신은 잭슨을 검색합니다. : D

샘플 코드.

(pom.xml 파일)

<!-- Jackson --> 
<dependency> 
    <groupId>com.fasterxml.jackson.core</groupId> 
    <artifactId>jackson-core</artifactId> 
    <version>2.4.3</version> 
</dependency> 
<dependency> 
    <groupId>com.fasterxml.jackson.core</groupId> 
    <artifactId>jackson-databind</artifactId> 
    <version>2.4.3</version> 
</dependency> 

(JS)

var list = new Array(); 

list.push(Your data); 

data = JSON.stringify(list); 
$.ajax({ 
     url : "your url", 
     type : 'POST', 
     data : data, 
     contentType : 'application/json', 

     success : function(response) { 

     }, 
     error : function(request, status, error) { 

     } 
}); 

(컨트롤러)

@RequestMapping(value = "your path", method = RequestMethod.POST) 
public @ResponseBody String test(@RequestBody List<TestModel> models) { 


    return null; // break point, check model. 
} 

당신은 모델을 만들 수 있습니다.