2016-07-12 6 views
1

私はコントローラにJSONとして渡している動的な名前と値のペアを持っています。AJAXポスト動的JSONオブジェクトMVCマッピング

例:動的JSONオブジェクトはjsonVehicleObjectは常にnullである jQueryの

以下
{"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); 
} 

を使用して生成されました。私はオブジェクトタイプとしてVehicleと共にRequestBodyを使用しようとしました。しかし、使用しないでください。助言がありますか?

答えて

0

AJAXでtype: 'Post'を使用している場合は、コントローラにリクエストタイプを追加する必要があることを意味します。

は、応答のタイプを定義するための方法において使用httpPost

[HttpPost] 
public void 
String saveVehicles(..) 

、コントローラでこれを使用してみてください。

0

あなたはjacksonを使用しています。 ジャクソンJSONから/へのJavaオブジェクトの変換

ジャクソンを検索します。 :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. 
} 

モデルを作成します。

関連する問題