将json数据与类属性匹配

时间:2017-02-08 15:10:57

标签: c# json asp.net-web-api2

我使用了一个webapi方法,其中[FromBody]我使用了我的类对象。 如下所示:

 public HttpResponseMessage ProcessResource([FromBody]FileContent contentvalue)
    {//some business logic
    }

以下是我从客户端机器发送的json格式:

 {"FileContent":{"ResourceStrings":[{"StringKey":"TestKey","StringID":1,"Value":"TestKey"},{"StringKey":"SampleKey","StringID":2,"Value":"Test key 1"},{"StringKey":"HomeKey","StringID":3,"Value":"Home DEV"},{"StringKey":"custom.WVF.ContactForm.Name","StringID":4,"Value":"NAME"},{"StringKey":"custom.CMS.MenuItem","StringID":5,"Value":"CMS.MenuItem"}]},}

下面是使用的FileContent类:

public class ResourceString
{
    public string StringKey { get; set; }
    /// <summary>
    /// Gets or sets the StringKey
    /// </summary>
    /// <value>
    /// StringKey
    /// </value>
    public int StringID { get; set; }
    /// <summary>
    /// Gets or sets the StringID
    /// </summary>
    /// <value>
    /// StringID
    /// </value>
    public string Value { get; set; }
    /// <summary>
    /// Gets or sets the Value
    /// </summary>
    /// <value>
    /// Value
    /// </value>
}
/// <summary>
/// Added RootObject new class to serialize and deserialize for resource string
/// </summary>
public class RootObject
{
    /// <summary>
    /// Gets or sets the list of ResourceString
    /// </summary>
    public List<ResourceString> ResourceStrings { get; set; }
}
public class FileContent
{
    public List<ResourceString> ResourceStrings { get; set; }
}

现在,当我从客户端计算机发送json数据并调试我的web api方法时,FileContent对象值为null。

如何在此方法参数中获取json数据?

现在我可以使用Roma的解决方案获取该方法中的json数据。 获取数据后我需要再次将其反序列化为ResourceString然后再次我应该得到我的json格式如下:

 {"ResourceStrings":[{"StringKey":"TestKey","StringID":1,"Value":"TestKey"},{"StringKey":"SampleKey","StringID":2,"Value":"Test key 1"},{"StringKey":"HomeKey","StringID":3,"Value":"Home DEV"},{"StringKey":"custom.WVF.ContactForm.Name","StringID":4,"Value":"NAME"},{"StringKey":"custom.CMS.MenuItem","StringID":5,"Value":"CMS.MenuItem"}]}

如何使其反序列化以获得相同的效果?

1 个答案:

答案 0 :(得分:1)

制作RootObject

public class RootObject
{
    public FileContent FileContent { get; set; }
}

将您的操作更改为:

public HttpResponseMessage ProcessResource([FromBody]RootObject obj)
{
    //some business logic
}

如果您要解析FileContentJSON应该是:

{"ResourceStrings":[{"StringKey":"TestKey","StringID":1,"Value":"TestKey"},{"StringKey":"SampleKey","StringID":2,"Value":"Test key 1"},{"StringKey":"HomeKey","StringID":3,"Value":"Home DEV"},{"StringKey":"custom.WVF.ContactForm.Name","StringID":4,"Value":"NAME"},{"StringKey":"custom.CMS.MenuItem","StringID":5,"Value":"CMS.MenuItem"}]}