2013-07-05 155 views
0

我想获得一个结构在JSON:C#对象到JSON转换

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

我可以用JavaScriptSerializer到.NET类转换成JSON格式。但女巫结构我的班级必须具备以上样本数据?

+0

不是一个确切的重复,但看看[JavaScriptSerializer.Deserialize - 如何更改字段名称](http://stackoverflow.com/questions/1100191/javascriptserializer-deserialize-how-to-change-field-名)。 – CodeCaster

回答

3

你有没有尝试过这样的:

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

您也可以使用DataContractJsonSerializer,而是你可以使用以下类:像你需要一个

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

[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; } 
} 
+2

你将不得不有forSale或东西作为待售不是一个财产的有效名称。 –

+0

@尼尔,的确,我会纠正它。 –

+0

如果您想添加额外的项目,此方法可能会导致问题。 –

0

看起来并添加数据,如:

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

当有简单的方法将JSON映射到POCO时,我不会采用这种方法。 –