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

时间:2013-02-25 13:15:43

标签: 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#方法和界面: 接口:

[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>

1 个答案:

答案 0 :(得分:2)

我认为这是因为它不喜欢您约会的格式 - 即'02 / 19/2013 12:00 pm'。尝试将C#Fixture Data Contract中的Date类型更改为字符串或编辑JS Fixture原型的toJSON方法,以返回格式为“2013-02-19Z”的字符串。