简体   繁体   中英

C# Object to JSON convert

I would like to get next structure in 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. 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:

[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")});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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