Nancy与使用JSON的Complex对象无法正常工作

时间:2014-07-10 13:24:00

标签: nancy

客户代码:

 var basket = {
            products: [],
            user: { name: "schugh" }
        };

    $("#basket table tr").each(function (index, item) {
        var product = $(item).data('product');
        if (product) {
            basket.products.push(product);
        }

    });

    $.ajax({
        url: "http://localhost:12116/basketrequest/1",
        async: true,
        cache: false,
        type: 'POST',
        data: JSON.stringify(basket),
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',

        success: function (result) {
            alert(result);
        },
        error: function (jqXHR, exception) {
            alert(exception);
        }
    });

服务器代码:

 Post["/basketrequest/{id}"] = parameters =>
 {     
     var basketRequest = this.Bind(); //basketrequest is null
     return Response.AsJson(basketRequest , HttpStatusCode.OK);
 };

其他模特课程:

[Serializable]
public class BasketRequest
{
    public User User;
    public List<Product> Products;
}

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Category { get; set; }
    public decimal Price { get; set; }
    public ProductStatus ProductStatus { get; set; }
}

public enum ProductStatus
{
    Created,
    CheckedBy,
    Published
}

public class User
{
    public string Name { get; set; }
}

南希模块this.Bind();中的代码返回null。如果我将Complex对象更改为List<Product>,即没有包装器BasketRequest,则对象很好......

任何指针?

编辑:JSON发布:

{
  "User": { 
    "Name": "SChugh" 
  },
  "Products": [{ 
    "Id": 1,
    "Name": "Tomato Soup",
    "Category": "Groceries",
    "Price": 1
  }, { 
    "Id": 2,
    "Name": "Yo-yo",
    "Category": "Toys",
    "Price": 3.75
  }]
}

1 个答案:

答案 0 :(得分:8)

您的BasketRequest对象应该实现属性而不是字段。所以

public class BasketRequest
{
    public User User { get; set; }
    public List<Product> Products { get; set; }
}

你也应该使用泛型方法

this.Bind<BasketRequest>();