简体   繁体   English

C#对象到JSON转换

[英]C# Object to JSON convert

I would like to get next structure in JSON: 我想在JSON中获取下一个结构:

{
    'for-sale': { name: 'For Sale', type: 'folder' },
    'vehicles': { name: 'Vehicles', type: 'folder' },
    'rentals': { name: 'Rentals', type: 'folder' },
}

I can use JavaScriptSerializer to convert .net class to JSON format. 我可以使用JavaScriptSerializer将.net类转换为JSON格式。 But witch structure my class must have for above sample data? 但是我班的巫婆结构必须具有上述示例数据?

Have you tried this: 您是否尝试过:

public class MyClass
{
    [JsonProperty("for-sale")]
    public IList<Item> forSale { get; set; }
    public IList<Item> vehicles { get; set; }
    public IList<Item> rentals { get; set; }
}

public class Item
{
    public string name { get; set; }
    public string type { get; set; }
}

You could also use the DataContractJsonSerializer and instead you would use the following classes: 您还可以使用DataContractJsonSerializer,而可以使用以下类:

[DataContract]
public class MyClass
{
    [DataMember(Name = "for-sale")]
    public IList<Item> forSale { get; set; }
    [DataMember]
    public IList<Item> vehicles { get; set; }
    [DataMember]
    public IList<Item> rentals { get; set; }
}

[DataContract]
public class Item
{
    [DataMember]
    public string name { get; set; }
    [DataMember]
    public string type { get; set; }
}

Looks like you need a 看起来你需要一个

var theStructure = Dictionary<string, Dictionary<string,string>>()

and add data to it like: 并向其中添加数据,例如:

theStructure.Add("for-sale", new Dictionary<string, string>() {("For Sale", "folder")});

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

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