【问题标题】:Loop through Json files and extract specific data循环遍历 Json 文件并提取特定数据
【发布时间】:2018-07-17 21:45:24
【问题描述】:

我有一堆 Json 文件在存储中,我可以在其中循环选择符合我标准的集合列表。尽管 Json 文件具有不同的数据和结构,但它们都有一个共同点 - 具有如下结构的元数据属性:

"meta": {
    "source": "user1",
    "createdDate": "2018-07-16T16:36:58.6471066+01:00",
    "recordCount": 12
},

我想提取每个文件的元数据并将结果存储在具有以下结构的新 DTO 中:

"data": [
{
    "source": "User1",
    "createdDate": "2018-07-16T16:36:58.6471066+01:00",
    "recordCount":12
},
    {
    "source": "User2",
    "createdDate": "2018-07-15T13:01:23.5611259+01:00",
    "recordCount":18
}
]

目前我的代码如下所示:

foreach (string s in objectType) //objectType is a simple string array for my file criteria
{
    var fileData = storage.GetS3(s, testOrg); //custom method to get file from storage, returns the json file contents using StreamReader. Returns null if no file found

    if (fileData != null) 
    {
        var response = JsonConvert.DeserializeObject(fileData);

        //extract metadata from file to populate DTO

    }
}

感谢任何帮助。总的来说,我是 c# 的新手,所以请放轻松!

我的 DTO 目前如下所示,但可以更改:

public class FileStatusResponse
{
    [JsonProperty("data")]
    public FileStatusDetail[] Data { get; set; }
}

public class FileStatusDetail
{
    [JsonProperty("source")]
    public string FileType { get; set; }

    [JsonProperty("recordCount")]
    public string RecordCount { get; set; }

    [JsonProperty("refreshDate")]
    public DateTime RefreshDate { get; set; }
}

【问题讨论】:

  • 由于它们都有不同的结构,而不是反序列化为对象,我会使用 json.Parse() 并直接访问字段。这是文档:newtonsoft.com/json/help/html/ParseJsonObject.htm
  • 您能否edit 分享您需要解析的一两个简单但完整且格式良好的 JSON 示例?您的问题中包含的 JSON 只是一个片段,因此根据jsonlint.com 格式不正确。例如,"meta" 属性是否始终位于 JSON 的根级别?

标签: c# json dto


【解决方案1】:

好的,我似乎已经对它进行了排序:

var fileStatusList = new List<FileStatusDetail>();
        var storage = new S3Manager();

        foreach (string s in objectType)
        {
            var fileData = storage.GetS3(s, organisationCode);

            if (fileData != null)
            {
                var parsedObject = JObject.Parse(fileData);
                var parsedJson = parsedObject["meta"].ToString();

                var json = JsonConvert.DeserializeObject<Metadata>(parsedJson);

                fileStatusList.Add(new FileStatusDetail
                {
                    source = s,
                    RecordCount = json.RecordCount,
                    RefreshDate = json.CreatedDate

                });

            }

        }

感谢 itsme86 为我指明了正确的方向

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-19
    • 1970-01-01
    • 2017-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-30
    相关资源
    最近更新 更多