反序列化具有不同类名的Json C#

2q5ifsrm  于 2023-01-18  发布在  C#
关注(0)|答案(1)|浏览(251)

我有一个Web服务,我得到了一个复杂的Json对象,一切正常,但在这个对象中有一个类,在每个响应中根据项目名称更改其名称,这阻止了正常的反序列化过程

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; }
}

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

1rhkuytd

1rhkuytd1#

我能够让这个配置工作:

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; }
}

我认为你的方法是正确的,你只需要将字典上移一层,允许键值对基于类名。这样就留下了DR7614060定义。只要给予它一个合适的类名用于反序列化。现在你的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中,我得到了:

相关问题