如何使用mvc spring将JSON数组插入MySQL

时间:2015-08-18 04:58:08

标签: mysql json angularjs spring spring-mvc

嗨,我是春天的新人,开发了一个POST模块。 如何在db中插入JSON数组。 能告诉我如何解决这个问题吗?

我还有一个例子向您展示。 链接: - http://hello-angularjs.appspot.com/angularjs-http-service-ajax-post-json-data-code-example

这里是控制器代码

@RequestMapping(value = "/create1", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody
BillingModel addbillingmodel(@RequestBody BillingModel billingmodel) {
    try { 


        billingmodel.getItemid();
        billingmodel.getQuantity();

        dataServices.addEntity(billingmodel); 


        return billingmodel;
    } catch (Exception e) {
         e.printStackTrace();
        return billingmodel;
    }

   }
  }

这是我的带有JSON的html页面。

<!DOCTYPE html>
<html data-ng-app="serviceModule">
<head>
<meta charset="ISO-8859-1">
<title>AngularJS POST Spring MVC</title>
<script    
src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js">   
</script>
<script type="text/javascript">

var serviceModule = angular.module('serviceModule', []);

serviceModule.controller("AngularJSPostController", function($scope, $http) {

        $scope.variable = "AngularJS POST Spring MVC Example:"; 
        var dataObj = {
                "itemid" : "11",
                "quantity" : "22",


        };      

        var response = 
   $http.post('/CRUDWebAppMavenized/billing_bakery/create1', dataObj);
        response.success(function(data, status, headers, config) {
            $scope.responseData = data;
        });
        response.error(function(data, status, headers, config) {
            alert( "Exception details: " + JSON.stringify({data: data}));
        });

    });

 </script>
 </head>
 <body data-ng-controller="AngularJSPostController"> 




  <div>
    <h4>{{variable}}</h4>
    <b>You had sent below data through post:</b>
    <p>Response:  {{responseData}}</p>      
  </div>

  </body>
</html>

我必须连续多个数据。

1 个答案:

答案 0 :(得分:0)

1.在您的BillingModel类中创建以下方法 -

     import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
     import com.fasterxml.jackson.core.JsonParseException;
     import com.fasterxml.jackson.core.JsonProcessingException;
     import com.fasterxml.jackson.databind.JsonMappingException;
     import com.fasterxml.jackson.databind.ObjectMapper;
     public String toJson() throws JsonProcessingException {
       ObjectMapper mapper = new ObjectMapper();
       String json = mapper.writeValueAsString(this);
       return json;
    }

2.你应该有blob类型的列来存储JSON

3.当您调用addEntity时,在您的DAO课程中,执行类似的操作 -

final MapSqlParameterSource sqlParams = new MapSqlParameterSource()
.addValue("item_json",billingModel.toJson().getBytes("UTF-8"));

您也可以参考。 Converting Java objects to JSON with Jackson