繁体   English   中英

使用不同的 Class 名称反序列化 Json C#

[英]Deserialize Json With Different Class Names C#

我有一个 web 服务,我得到一个复杂的 Json object,一切都很好,但是这个 object 中有一个 class 根据项目名称在每个响应中更改其名称,这阻止了正常的反序列化过程

public class Threads
{
    public object threads { get; set; }
    public object error { get; set; }
    public Async async { get; set; }
    public Products products { get; set; } => Products Class
}


public class Products
{
    //public DR7614060 dr7614060 { get; set; }
    
    // I try to Deserialize the class as  Dictionary but nothing happend
    Dictionary<string, DR7614060> Pairs { get ; set; }
}


public class DR7614060
{
    public string id { get; set; }
    public string threadId { get; set; }
    public string productId { get; set; }
    public bool mainColor { get; set; }
    public Productrollup productRollup { get; set; }
}

Json:

https://github.com/Kremed/ContenPageFlowDirection/blob/master/Json.json

我能够让这个配置工作:

public class Threads
{
    [JsonProperty("threads")]
    public object ThreadsThreads { get; set; }

    [JsonProperty("error")]
    public object Error { get; set; }

    [JsonProperty("async")]
    public ThreadsAsync Async { get; set; }

    [JsonProperty("products")]
    public Dictionary<string, StupidClassName> Products { get; set; }
}

我认为你走在正确的轨道上,你只需要将字典向上移动一级以允许键值对基于 class 的名称。这样就留下了DR7614060定义。 只需给它一个正确的 class 名称即可用于反序列化。 现在你的Products字典将有 key = 'given class name' value = 'deserialized object with defined class name'

public partial class StupidClassName // instead of DMxxxxxx
{
    [JsonProperty("id")]
    public Guid Id { get; set; }

    [JsonProperty("threadId")]
    public Guid ThreadId { get; set; }

    [JsonProperty("productId")]
    [JsonConverter(typeof(ParseStringConverter))]
    public long ProductId { get; set; }

    [JsonProperty("mainColor")]
    public bool MainColor { get; set; }

    [JsonProperty("productRollup")]
    public ProductRollup ProductRollup { get; set; }
    // .... more props etc.
 }

从您发布的 Json 我得到:

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM