繁体   English   中英

C#在JSON对象中序列化JSON对象

[英]C# Serialize JSON object within JSON objects

我有这些实体:

public class Product
{
    public string Code {get;set;}
    public string Name {get;set;}

    public ICollection<Pack> Packs {get;set;}
}

public class Pack
{
    public string Colour {get;set;}
    public string Moq {get;set;}
}

我的json对象:

var products = [{
    code: 1243123,
    name: "Gel",
    packs: [{
        color: "blue",
        moq: 10
    }]
}];

请注意命名差异,即颜色的大小写和美国拼写。 JavaScriptConvert.DeserializeObject()会正确反序列化吗?

还是我必须另辟?径?

如果我只有一个可以直接访问这些名称的对象,那么那里的值将是巨大的!

如果使用JSON.NET之类的东西 ,则可以使用属性来控制序列化,例如:

public class Pack
{
    [JsonProperty("color")]
    public string Colour {get;set;}
    [JsonProperty("moq")]
    public string Moq {get;set;}
}

另外,鉴于您的预期输出,您的Product类应如下所示:

public class Product
{
    [JsonProperty("code")]
    public long Code {get;set;}
    [JsonProperty("name")]
    public string Name {get;set;}
    [JsonProperty("packs")]
    public Pack[] Packs {get;set;}
}

注意代码类型。

如果改用DataContractJsonSerializer ,则可以将属性放入属性,在生成/解析的JSON中为它们赋予不同的名称:

[DataContract]
public class Pack
{
    [DataMember(Name = "color")]
    public string Colour {get;set;}

    [DataMember(Name = "moq")]
    public string Moq {get;set;}
}

暂无
暂无

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

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