1

当我制作mvc ajax json post applicaiton时,将json动态对象转换为实体存在问题。

在我的应用程序中,电影是一个业务实体,json 对象比电影实体具有行状态属性。json数据发布到mvc服务器端后,可以转换为动态对象,这个阶段一切正常。但是在对每一行状态进行一些逻辑处理后,需要将动态对象转换为电影业务实体,然后开始数据库事务逻辑。但是即使我尝试不同的方法来投射对象,也有一个问题。

请问有人使用相同的演员方法吗?感谢您的建议或回复。

public class movie
{
    public int id
    {
        get;
        set;
    }

    public string title
    {
        get;
        set;
    }
}



    /// <summary>
    /// Convert Json Object to Entity
    /// </summary>
    /// <param name="id">ajax post value
    /// format: {"id": "{\"id\": 1, \"title\": \"sharlock\", \"RowStatus\": \"deleted\"}"}
    /// </param>
    [AllowAnonymous]
    [HttpPost]
    public void DoJsonSimple(string id)
    {
        string title;
        var entity = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(id);

        //*** entity is dynamic object
        //*** entity.id, entity.title and entity.RowStauts can be accessed.
        int first = entity.id;
        var status = entity.RowStatus;
        if (status == "deleted")
        {
            //*** m1 is null
            //*** m1.title can not be accessed
            movie m1 = entity as movie;
            title = m1.title;

            //*** m2 is an empty object
            //*** m2.id is 0, m2.title is null
            var m2 = AutoMapperHelper<dynamic, movie>.AutoConvertDynamic(entity);
            title = m2.title;

            //*** Exception: Object must implement IConvertible. 
            var m3 = EmitMapper.EMConvert.ChangeTypeGeneric<dynamic, movie>(entity);
            title = m3.title;
        }
    }
4

1 回答 1

2

只需为行创建另一个类。

public class Request
{
    [JsonProperty("id")]
    public string Json { get; set; }
}

public class Movie
{
    [JsonProperty("id")]
    public int Id { get; set; }

    [JsonProperty("title")]
    public string Title { get; set; }
}

// either this for variant 1...
public class Row
{
    public string RowStatus { get; set; }
}

// or that for variant 2...
public class MovieRow : Movie
{
    public string RowStatus { get; set; }
}

[AllowAnonymous]
[HttpPost]
public void DoJsonSimple_Variant1(string id)
{
    var json = JsonConvert.DeserializeObject<Request>(id).Json;
    var entity = JsonConvert.DeserializeObject<MovieRow>(json);
    var row = JsonConvert.DeserializeObject<Row>(json);

    switch (row.RowStatus)
    {
        case "deleted":
            // delete entity
            break;

        // ...
    }

    // ...
}

[AllowAnonymous]
[HttpPost]
public void DoJsonSimple_Variant2(string id)
{
    var json = JsonConvert.DeserializeObject<Request>(id).Json;
    var row = JsonConvert.DeserializeObject<MovieRow>(json);
    var entity = (Movie)row;

    switch (row.RowStatus)
    {
        case "deleted":
            // delete entity
            break;

        // ...
    }

    // ...
}
于 2013-03-29T02:34:10.267 回答