列表未使用我的json文件中的数据更新

时间:2019-07-11 01:41:11

标签: c# json

我目前正在做一项作业,我需要用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"
  }
}

1 个答案:

答案 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);

注意:

演示小提琴here