无法对nullable int 32类型进行反序列化

时间:2015-03-02 17:56:50

标签: json asp.net-web-api jsonserializer

我正在创建一个web api来创建一个驱动器。带脚本的html代码如下:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>

    <div>
    <h2>All Drives</h2>
    <ul id="drives" />
  </div>

<div>
    <h2>Insert New Drive</h2>
    <table>
     <tr>
         <td>Details : </td>
         <td>
             <input type="text" id="details" /></td>
     </tr>
        <tr>
            <td>Dollars Raised :</td>
            <td><input type="number" id="dollarRaised"  /></td>
        </tr>
        <tr>
            <td> Donation :</td>
            <td><input type="number" id="donationCount"  /></td>
        </tr>
        <tr>
            <td>Email : </td>
            <td><input type="email" id="email"  /></td>
        </tr>
        <tr>
            <td>location:</td>
            <td>
                <input type="text" id="location" />

            </td>
        </tr>
        <tr>
            <td>Organizer:</td>
            <td>
                <input type="text" id="organizer" />
            </td>

        </tr>
        <tr>
            <td>Title</td>
            <td>
                <input type="text" id="title" />
            </td>

        </tr>
        <tr>
            <td> Starting Date:</td>
            <td>
                <input type="date"  id="startDate"/>

            </td>

        </tr>
        <tr>
            <td> Ending Date:</td>
            <td>
                <input type="date"  id="endDate"/>

            </td>

        </tr>
        <tr>
            <td>Phone number: </td>
            <td><input type="tel" id="phone"  /></td>
        </tr>
        <tr>
            <td> Match Count:</td>
            <td>
               <input type="number" id="matchCount"/>
            </td>

        </tr>
        <tr>
            <td>Swab Count:</td>
            <td>
               <input type="number" id="swabCount"/>
            </td>

        </tr>
        <tr>
            <td>Duration</td>
            <td>
              <input type="number" id="duration"/>
            </td>

        </tr>
        <tr>
            <td colspan="2"> <input type="button" value="Save" onclick="Post();" /></td>
        </tr>
    </table>
    <p id="P1" />
  </div>
    <h2>Here displays returned data from web api</h2>
    <div id="divResult">

    </div>
    <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>

  <script>
      var uri = 'api/drive';

      $(document).ready(function () {
          // Send an AJAX request
          getdrivelist();
      });


      function getdrivelist() {
          $.getJSON(uri)
             .done(function (data) {
                 $('#drives').html('');
                 // On success, 'data' contains a list of drives.
                 $.each(data, function (key, item) {
                     // Add a list item for the drive.

                     $('<li>', { text: formatItem(item) }).appendTo($('#drives'));
                 });
             });
      }
      function formatItem(item) {
          return 'Title:' + item.title + ' and Details:' + item.details + ' From: ' + item.startDate + 'To:  ' + item.endDate + 'organizer' + item.organizer ;


      }
      function Post() {
          jQuery.support.cors = true;
          var source = {
              'DriveID': 0,
              'details': $('#details').val(),
              'dollarRaised': $('#dollarRaised').val(),
              'email': $('#email').val(),
              'phone': $('#phone').val(),
              'donationCount': $('#donationCount').val(),
              'location': $('#location').val(),
              'organizer': $('#organizer').val(),
              'endDate': $('#endDate').val(),
              'startDate': $('#startDate').val(),
              'matchCount': $('#matchCount').val(),
              'swabCount': $('#swabCount').val(),
              'title': $('#title').val(),
              'duration': $('#duration').val(),
              'UserID':0
          }
          $.ajax({
              type: "POST",
              dataType: "json",
              url: "/api/drive",
              data: source,
              success: function (data) {
                  getdrivelist();
              },
              error: function (x, y, z) {
                  //jsonValue = jQuery.parseJSON(error.responseText);
                  var strResult = "<table><th>Error Message</th>";
                  // $.each(data, function (index, data) {
                  strResult += "<tr><td> " + x.responseText + " </td></tr>"
                  strResult += "</table>";
                  $("#divResult").html(strResult);

                  //jError('An error has occurred while saving the new part source: ' + jsonValue, { TimeShown: 3000 });
              }

          });
      }


  </script>
    </body>
    </html>

现在我调用post方法,如下所示:

public HttpResponseMessage Post([FromBody] JObject drivedata)
        {

            var jsonInput = drivedata.ToString();

            JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
            Drive drive = jsonSerializer.Deserialize<Drive>(jsonInput);
            if (drive.title.Equals(""))
            {
                var message = string.Format("Title required");
                HttpError err = new HttpError(message);

                HttpResponseMessage response1 = Request.CreateResponse(HttpStatusCode.BadRequest, err);
                return response1;
            }
            else
            {
                if (ModelState.IsValid)
                {
                    try
                    {

                        db.Drives.Add(drive);
                        db.SaveChanges();
                    }
                    catch (DbEntityValidationException ex)
                    {
                        // Retrieve the error messages as a list of strings.
                        var errorMessages = ex.EntityValidationErrors
                                .SelectMany(x => x.ValidationErrors)
                                .Select(x => x.ErrorMessage);



                        // Join the list to a single string.
                        var fullErrorMessage = string.Join("; ", errorMessages);

                        // Combine the original exception message with the new one.
                        var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage);

                        // Throw a new DbEntityValidationException with the improved exception message.
                        throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors);

                    }
                    HttpResponseMessage response = Request.CreateResponse<Drive>(HttpStatusCode.Created, drive);
                    //response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = user.UserID }));
                    return response;
                }
                else
                {
                    return Request.CreateResponse(HttpStatusCode.BadRequest);
                }
            }
        }

当我调用post方法时,在我将json对象反序列化为Drive对象的行上,它给出了如下错误:“不是int32的有效值” 我已经尝试过动态对象,但没有运气。 我无法对nullable int 32类型进行反序列化。在Drive表中的一些属性是int32和nullable我试图在添加新记录时保留空值。这意味着, 当用户在输入新记录或驱动器时将该字段留空时。 属性donationCount =“”但我希望它存储null而不是为空。但由于属性类型为int32,它不能存储null并给出错误

1 个答案:

答案 0 :(得分:0)

您正在尝试将空字符串反序列化为可以为null的int属性。这不起作用,因为字符串不能适合整数,空字符串与空值不同。 json值必须是数字或null。

根据您提供的信息,我不知道哪个属性导致了问题,但您应该可以自己轻松找到它。然后,确保使用javascript函数parseInt(str)将字符串转换为有效的Number对象,因为执行ajax调用。它应该是这样的:

var source = {
    ...
    someNumericValue: parseInt($('#someId').val()),
    ...
};