在C#

时间:2019-12-26 05:36:09

标签: c# json csv json.net

我已经引用了Convert nested JSON to CSV,但不适用于我的情况。由于缺少某些层次结构,因此无法正常工作。 我的json样本是

{
  "data": {
    "getUsers": [
      {
        "userProfileDetail": {
          "userStatus": {
            "name": "Expired"
          },
          "userStatusDate": "2017-04-04T07:48:25+00:00",
          "lastAttestationDate": "2019-02-01T03:50:42.6049634-05:00"
        },
        "userInformation": {
          "Id": 13610875,
          "lastName": "************",
          "suffix": null,
          "gender": "FEMALE",
          "birthDate": "1970-01-01T00:01:00+00:00",
          "ssn": "000000000",
          "ethnicity": "INVALID_REFERENCE_VALUE",
          "languagesSpoken": null,
          "personalEmail": null,
          "otherNames": null,
          "userType": {
            "name": "APN"
          },
          "primaryuserState": "CO",
          "otheruserState": [
            "CO"
          ],
          "practiceSetting": "INPATIENT_ONLY",
          "primaryEmail": "*****@*****.com"
        }
      }
    ]
  }
}

代码是

var obj = JObject.Parse(json);
            // Collect column titles: all property names whose values are of type JValue, distinct, in order of encountering them.
            var jsonValues = obj.DescendantsAndSelf().OfType<JProperty>().Where(p => p.Value is JValue).GroupBy(p => p.Name).ToList();
            var jsonKey = jsonValues.Select(g => g.Key).ToArray();

            // Filter JObjects that have child objects that have values.
            var parentsWithChildren = jsonValues.SelectMany(g => g).SelectMany(v => v.AncestorsAndSelf().OfType<JObject>().Skip(1)).ToHashSet();

            // Collect all data rows: for every object, go through the column titles and get the value of that property in the closest ancestor or self that has a value of that name.
            var rows = obj
                .DescendantsAndSelf()
                .OfType<JObject>()
                .Where(o => o.PropertyValues().OfType<JValue>().Any() && (o == obj || !parentsWithChildren.Contains(o))) // Show a row for the root object + objects that have no children.
                .Select(o => jsonKey.Select(c => o.AncestorsAndSelf().OfType<JObject>().Select(parent => parent[c])
                    .Where(v => v is JValue).Select(v => (string)v).FirstOrDefault()).Reverse() // Trim trailing nulls
                    .SkipWhile(s => s == null).Reverse());

            // Convert to CSV
            var csvRows = new[] { jsonKey }.Concat(rows).Select(r => string.Join(",", r));
            var csv = string.Join("\n", csvRows);
            File.WriteAllLines(@"E:/Temp/dotnet/JSON2CSV/Samples.csv", csvRows); // 
            Console.WriteLine(csv);

输出为 output csv

输出与预期不符,bcs'apn'不在第一列下并且缺少“ otheruserState”:[             “ CO”           ],值

0 个答案:

没有答案