我正在尝试创建一个类库,它允许我从列表中读取数据,然后以json格式输出数据。下面是一个客户希望我模仿的json屏幕截图。我相信想要使用json.net库来创建这个json文件,但是我很难理解如何创建c#类和集合,以便获得下面指定的输出。
顶级对象应该是OEM对象,所以我希望在您看到"7“、"8”、"27“、"49”、"16“的地方看到"OEM”。
例如,如果我的OEM类如下所示:
public class OEM
{
public int OemID { get; set; }
}
创建json的代码是:
List<asbs.OEM> Oems = new List<asbs.OEM>();
asbs.OEM oem = new asbs.OEM() { OemID = 7 };
Oems.Add(oem);
string json = JsonConvert.SerializeObject(Oems, Formatting.Indented);
this._txt_Output.Text = json;
输出结果如下:
[
{
"OemID": 7
}
]
如何使对象被命名为"7“而不是OemId?这是可能的还是json文件不利于通过使用像我的OEM对象这样的可重用对象来创建?
发布于 2013-08-31 00:12:21
让OEM ids以数字属性名称序列化的一种方法是将它们放入字典中,并将其序列化,而不是Oems
列表。以下是您如何轻松地做到这一点:
// Original list of OEM objects
List<asbs.OEM> Oems = new List<asbs.OEM>();
Oems.Add(new asbs.OEM() { OemID = 7 });
Oems.Add(new asbs.OEM() { OemID = 8 });
Oems.Add(new asbs.OEM() { OemID = 27 });
// Create a new dictionary from the list, using the OemIDs as keys
Dictionary<int, asbs.OEM> dict = Oems.ToDictionary(o => o.OemID);
// Now serialize the dictionary
string json = JsonConvert.SerializeObject(dict, Formatting.Indented);
您还可能希望用OemID属性修饰[JsonIgnore]
属性,以便它不包含在序列化输出的其他地方(除非您希望它在那里)。
对于其他属性,如果这些属性在类中的命名方式与您希望序列化的输出不同,则可以使用[JsonProperty]
属性来控制这些属性。
public class OEM
{
[JsonIgnore]
public int OemID { get; set; }
[JsonProperty(PropertyName="cars")]
public CarInfo Cars { get; set; }
[JsonProperty(PropertyName = "suvs")]
public CarInfo Suvs { get; set; }
// other properties
}
这应该足以让你开始工作了。如果您需要对输出进行更多的控制,您可以考虑为您的JsonConverter
类创建一个自定义OEM
。
发布于 2013-08-30 22:26:00
这是因为您有一个对象列表或数组。您提供的JSON只是一个包含嵌套对象的对象。基本上是一种经验法则;
看到“propertyName”的任何地方:{.}在C#代码中看到"propertyName":.您需要一个封闭类型的List<T>
或T[]
(数组)。您必须编写一个自定义序列化程序,因为整数在C#中不是有效的属性名称,而且示例json中的一组对象的名称类似于"7“。
所以,要为你做一点事情,你需要这样的东西;
public class jsonWrapper
{
public Seven seven { get; set; }
}
public class Seven
{
public All all { get; set; }
}
public class All
{
public Cars cars { get; set; }
}
public class Cars
{
public Portrait Portrait { get; set; }
}
public class Portrait
{
public Landscape Landscape { get; set; }
}
public class Landscape
{
public Background Background { get; set; }
}
public class Background
{
public Element[] Elements { get; set; } // the only array I see in your json
}
public class Element
{
//properties that you have collapsed
}
https://stackoverflow.com/questions/18542075
复制相似问题