我正在处理一个模型,其中包含一个列表。
我需要将列表展平为主对象,即JSON文件。
因此,我需要将其展平,如下所示:示例:
{
name: Test1
startDate: 6/6/2020
endDate: 6/7/2020
assetId: 8
locationId: 10
}C#类模型如下所示:
public string name { get; set; }
public DateTime startDate { get; set; }
public DateTime endDate { get; set; }
public List<Resources> ResourcesList { get; set; }这将是类Resources:
public string Type { get; set; }
public int Id { get; set; }然后,源的值将是:
new Resources { Type = "assetId", Id = 8 }
new Resources { Type = "locationId", Id = 10 }发布于 2020-06-07 14:05:26
你的问题是"C# Object flatten to JSON structure“。
文章中的顶部文本块不能用作JSON,所以让我们确保JSON是您想要的,因为它的作用是将对象存储为字符串(序列化它),同时保留值和内部结构。可能是将对象保存到文件中,或者通过HTTP将其发送到服务器。无论哪种方式,您都可以这样做:
string jsonSerialize = JsonConvert.SerializeObject(classModelObject, Formatting.Indented);现在它是一个字符串。日期、整数、浮点数都以字符串格式表示。你的代码看起来像这样:
{
"name":"Test1",
"startDate":"2020-06-06T00:00:00",
"endDate":"2020-06-07T00:00:00",
"ResourcesList": [
{"Type":"assetId","Id":8},
{"Type":"locationId","Id":10}
]
}如果您将该字符串存储到名为"class_model.json“的文件中,则像下面的this answer一样,如何将其转换回保留有资源列表的ClassModel对象:
ClassModel classModel = JsonConvert.DeserializeObject<ClassModel>(jsonSerialize);如果要将对象发送到web服务器,请按照this answer中所示进行操作
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://url");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(jsonSerialize);
}但是,如果您的目标应用程序与这两个应用程序非常不同,请先解释一下您为什么要使用JSON,以便我可以改进这个答案。
https://stackoverflow.com/questions/62240156
复制相似问题