c# - 创建可以在 C# 中反序列化的 JSON 对象

标签 c# javascript jquery json wcf

我正在尝试创建一个可以作为 C# 对象读取的 JSON 对象,当我尝试通过 AJAX 发送它时,我不断收到 400 错误请求错误。

我的 JavaScript 如下:

$.ajax({
type: "POST",
url: "LeagueService.svc/Fixtures",
    data: JSON.stringify(fixture),
    dataType: "json",
    contentType: "application/json",
    success: function (json, status, req) {
        $successMessage = '<div class="hero-unit"><h2>Success</h2><p>The fixture has been added to the database.</p></div>';

        $('#dialog').html($successMessage).fadeOut(500, function (e) {
            $(this).dialog("close");
        });

     },
     error: function (req, status, error) {
       alert('Error: ' + req.responseText);
     }
});

我的 Fixture 对象看起来像:

function Fixture() { }

Fixture.prototype =
{
    ID: "",
    HomeTeam: "",
    AwayTeam: "",
    Date: "",

    toJSON: function () { return { "fixture": {"ID" : this.ID, "HomeTeam" : this.HomeTeam, "AwayTeam" : this.AwayTeam, "Date" : this.Date} }; }
};

这种方法在我编写的其他函数中运行得非常好,所以我不确定现在出了什么问题。

我的C#方法和接口(interface): 界面:

[OperationContract]
[WebInvoke(Method = "POST",
    BodyStyle = WebMessageBodyStyle.Wrapped,
    RequestFormat = WebMessageFormat.Json,
    ResponseFormat = WebMessageFormat.Json,
    UriTemplate = "/Fixtures")]
void AddFixture(Fixture fixture);

方法:

public void AddFixture(Fixture fixture)
{
    using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.DBConnect))
    {
        try
        {
            conn.Open();
            string query = "INSERT INTO tbFixtures (HomeTeam, AwayTeam, Date) VALUES(@HT, @AT, @Date);";
            using (SqlCommand cmd = new SqlCommand(query, conn))
            {
                cmd.Parameters.AddWithValue("@HT", fixture.HomeTeam.ID);
                cmd.Parameters.AddWithValue("@AT", fixture.AwayTeam.ID);
                cmd.Parameters.AddWithValue("@Date", fixture.Date);

                cmd.ExecuteNonQuery();
            }
        }
        catch (Exception) { }
        finally
        {
            conn.Close();
        }
    }
}

和 C# 类:

[DataContract(Name="Fixture", Namespace="")]
public class Fixture
{
    [DataMember(Name = "ID", Order = 1)]
    public int ID { get; set; }

    [DataMember(Name = "HomeTeam", Order = 2)]
    public Team HomeTeam { get; set; }

    [DataMember(Name = "AwayTeam", Order = 3)]
    public Team AwayTeam { get; set; }

    [DataMember(Name = "Date", Order = 4)]
    public DateTime Date { get; set; }
}

[DataContract(Name = "Team", Namespace = "")]
public class Team
{
    [DataMember(Name = "ID", Order = 1)]
    public int ID { get; set; }

    [DataMember(Name = "Name", Order = 2)]
    public string Name { get; set; }

    [DataMember(Name = "Wins", Order = 3)]
    public int Wins { get; set; }

    [DataMember(Name = "Losses", Order = 4)]
    public int Losses { get; set; }

    [DataMember(Name = "Draws", Order = 5)]
    public int Draws { get; set; }

    [DataMember(Name = "GoalsConceded", Order = 6)]
    public int GoalsConceded { get; set; }

    [DataMember(Name = "GoalsScored", Order = 7)]
    public int GoalsScored { get; set; }

    [DataMember(Name = "Manager", Order = 8)]
    public Manager Manager { get; set; }
}

[DataContract(Name = "Manager", Namespace = "")]
public class Manager
{
    [DataMember(Name = "ID", Order = 1)]
    public int ID { get; set; }
    [DataMember(Name = "Name", Order = 2)]
    public string Name { get; set; }
}

Manager 和 Team 类的编写方式与 JavaScript 中的 Fixture 类完全相同。

对象序列化为我认为正确的 JSON,但如果我遇到这些错误,显然不是。 生成的JSON如下:

{ "fixture": {
    "ID":0,
    "HomeTeam":{
        "ID":1,
        "Name":"Rhondda St FC",
        "Wins":21,
        "Losses":2,
        "Draws":4,
        "GoalsConceded":20,
        "GoalsScored":36,
        "Manager": {
            "ID":1,
            "Name":"Ron Burgundy"
        }
    },
    "AwayTeam": {
        "ID":2,
        "Name":"Mt Pleasant United FC",
        "Wins":18,
        "Losses":5,
        "Draws":3,
        "GoalsConceded":22,
        "GoalsScored":28,
        "Manager": { 
            "ID":2,
            "Name":"Brian Fantana"
        }
    },
    "Date":"02/19/2013 12:00pm"
}} 

如果有人能阐明这一点,我们将不胜感激。谢谢!

编辑:完整的错误(没有 CSS)是:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>Request Error</title>
   </head>
  <body>
    <div id="content">
      <p class="heading1">Request Error</p>
      <p xmlns="">The server encountered an error processing the request. Please see the <a rel="help-page" href="http://localhost:55310/LeagueService.svc/help">service help page</a> for constructing valid requests to the service.</p>
    </div>
  </body>
</html>

最佳答案

我认为这是因为它不喜欢您日期的格式 - 即“02/19/2013 12:00pm”。尝试将 C# 夹具数据协定中的日期类型更改为字符串,或编辑 JS 夹具原型(prototype)的 toJSON 方法以返回格式为“2013-02-19Z”的字符串。

关于c# - 创建可以在 C# 中反序列化的 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15067875/

相关文章:

javascript - 找不到模块'../../image/image.jpg

javascript - 如何每1-3秒调用一个函数?

javascript - 变量在 jQuery/JS 中不递增?

jquery - 新 HandsOnTable 版本中不显示滚动条

javascript - 如何使用 JavaScript/jQuery 找到两个元素节点之间的所有文本节点?

javascript - 在 ASP.NET Web API 2 项目中为 Angular 设置路由

javascript - 我是否需要使用三个 javascript 库来通过 ASP.NET MVC 4 进行验证?

c# - 当枚举类型也像字符串一样命名时,来自字符串的 ParseEnum

c# - 当应用程序有很多调用时如何管理连接池限制?

c# - 如何更改 netstandard 2.0 库使用的 Newtonsoft.Json 版本