我目前正在做一项作业,我需要用json文件中的数据更新列表。但是,我的清单一直显示为空,而且我似乎找不到找到任何帮助的理由。
我一直在尝试环顾四周,但是我所看到的许多问题只是提到如何提取数据而不是如何解决此问题。
我的课程和代码:
public class input
{
DateTime signed;
DateTime portal;
public DateTime Signed { get => signed; set => signed = value; }
public DateTime Portal { get => portal; set => portal = value; }
}
public class InputCollection
{
private List<input> inputs;
public List<input> Inputs { get => inputs; set => inputs = value; }
}
using (StreamReader streamReader = new StreamReader("C:\\Users\\Dominik\\Documents\\SenateCodingExercise\\CodingAssignment\\CodingAssignment\\input.json"))
{
//Reads all the data in the file
string json = streamReader.ReadToEnd();
//converting json string to a serious of objects
InputCollection inputCollection = JsonConvert.DeserializeObject<InputCollection>(json);
Console.WriteLine(inputCollection.Inputs.Count);
}
我的JSON文件如下所示:
{
"Schmidt, Wayne": {
"signed": "Friday, June 14, 2019 @ 10:58:21 PM"
},
"Hertel, Curtis": {
"portal": "Wednesday, June 5, 2019 @ 10:30:36 AM"
},
"Daley, Kevin": {
"signed": "Tuesday, June 4, 2019 @ 4:07:17 PM"
}
}
答案 0 :(得分:0)
您可以将JSON反序列化为Dictionary<string, Input>
,如 Deserialize a Dictionary 和this answer所示为 How can I parse a JSON string that would cause illegal C# identifiers? ,但是您需要对DateTime
格式进行一些修改。
首先,如下修改您的Input
模型:
public class Input
{
public DateTime? Signed { get; set; }
public DateTime? Portal { get; set; }
}
然后使用以下设置反序列化和重新序列化:
var settings = new JsonSerializerSettings
{
// Account for the custom DateTime format.
DateFormatString = "dddd, MMMM d, yyyy @ h:mm:ss tt",
// Do not re-serialize null `DateTime?` properties.
NullValueHandling = NullValueHandling.Ignore,
// Convert named c# properties -- but not dictionary keys -- to camel case
ContractResolver = new DefaultContractResolver { NamingStrategy = new CamelCaseNamingStrategy() },
};
var inputs = JsonConvert.DeserializeObject<Dictionary<string, Input>>(json, settings);
var outputJson = JsonConvert.SerializeObject(inputs, Formatting.Indented, settings);
注意:
由于某些JSON条目同时没有Signed
和Portal
值,因此将c#属性设置为nullable可以跟踪值是否实际上是出现在JSON中。
我修改了您的类名Input
以匹配c#命名约定。
Json.NET通过JsonSerializerSettings.DateFormatString
设置支持自定义DateTime
格式。各种格式选项的文档可在 Custom date and time format strings 中找到。
演示小提琴here。