用Json.Net反序列化嵌套对象



我正在处理一个返回如下内容的API:

{"v1.ProjectList": 
    { 
        "self_link": { "href": "https://central-staged:8880/api/v1/projects", "methods": "GET" }, 
        "items": [], 
        "register": {"href": "https://central-staged:8880/api/v1/projects/register", "methods": "POST"}, 
        "max_active": {"href": "https://central-staged:8880/api/v1/projects/max-active", "methods": "GET"} 
    }
}

我正在生成一堆dto来适应JSON字符串的反序列化。

namespace v1
{
    public class Project
    {
        public rest_common.Link branches { get; set; }
        public float coordinate_x { get; set; }
        public float coordinate_y { get; set; }
        public string description { get; set; }
        public int id { get; set; }
        public string location { get; set; }
        public string name { get; set; }
        public rest_common.Link publish_events { get; set; }
        public rest_common.Link self_link { get; set; }
        public rest_common.Link thumbnail { get; set; }
        public System.Guid uuid { get; set; }
    }
    [JsonObject(Title = "v1.ProjectList")]
    public class ProjectList
    {
        public List<Project> items { get; set; }
        public rest_common.Link max_active { get; set; }
        public rest_common.Link register { get; set; }
        public rest_common.Link self_link { get; set; }
    }
}
namespace rest_common
{
    public class Link
    {
        public string href { get; set; }
        public string methods { get; set; }
    }
}

该代码是从服务器端代码生成的,我可以修改它以适应。此时我唯一不能修改的是服务器返回的JSON响应。

我正在想办法把这个反序列化:

class Program
    {
        static void Main(string[] args)
        {
            var jsonContent = "{"v1.ProjectList": {"self_link": {"href": "https://something.com/getblah", "methods": "GET"}, "items": [], "register": {"href": "https://something.com/postblah", "methods": "POST"}, "max_active": {"href": "https://something.com/getblah2", "methods": "GET"}}}";
            var projectList = JsonConvert.DeserializeObject<ProjectList>(jsonContent);
            Console.ReadLine();
        }
    }

目前projectList是正确类的一个实例,但它的所有成员都是null

您正在尝试反序列化一个包含单个名为v1.ProjectList的属性的对象。所以创建这样的类:

public class ProxyObject
{
    [JsonPropertyAttribute("v1.ProjectList")]
    public ProjectList ProjectList { get; set;}
}

. .然后这个就行了:

var projectList = JsonConvert.DeserializeObject<ProxyObject>(jsonContent).ProjectList;

不需要[JsonObject(Title = "v1.ProjectList")]属性

由于您正在创建要从中反序列化JSON字符串的类的新实例,因此请指出:

var projectList = new (ProjectList)(JsonConvert.DeserializeObject<ProjectList>(jsonContent));

相关内容

  • 没有找到相关文章

最新更新