将JSON从一种结构转换为另一种结构

时间:2019-04-05 08:29:36

标签: c# json object dynamic

我有一种情况想尽我所能。我有一些我不关心的JSON,除了某些值。我只想提取这些值并将它们添加到新对象中。

这是我要开始使用的JSON:

{
  "name": "Codex JJ",
  "component": {
    "Profile-1": {
      "id": "Profile",
      "type": "Person",
      "attributes": {
                "Hair-color": "blue",
      "Eye-color": "brown",
        "hair-color": "brown",
        "height": "170cm"
      },
      "status": {
        "employed": "true",
        "ethnic": "White"
      }
    },
    "Profile-2": {
      "id": "Profile",
      "type": "Person",
      "attributes": {
                "Hair-color": "blue",
      "Eye-color": "brown",
        "hair-color": "brown",
        "height": "170cm"
      },
      "status": {
        "employed": "true",
        "ethnic": "White"
      }
    }
  }
}

我想将其重构为此JSON:

{
    "name": "NEW JSON"
    "company": [
        {
            "Person": "new-person",
            "attributes": {
                "Hair-color": "blue",
                "Eye-color": "brown",
                "employed": "true",
                "ethnic": "White"
            },
        {
            "Person": "new-person",
            "attributes": {
                "Hair-color": "blue",
                "Eye-color": "brown",
                "employed": "true",
                "ethnic": "White"
            },
        }
    ]
}

实施此最佳做法是什么?是否应该使用dynamic关键字反序列化传入的JSON?如何精确地提取值并将其添加到我创建的C#对象中,以生成一个全新的JSON结构?

2 个答案:

答案 0 :(得分:1)

如果您只想转换JSON而又不需要(或不需要)一个正式的对象模型来表示数据,则可以使用Json.NetLINQ-to-JSON API(JObjects)做到:

JObject obj = JObject.Parse(json);

JObject newObj = new JObject(
    new JProperty("name", obj["name"]),
    new JProperty("company", new JArray(
        obj["component"]
            .Children<JProperty>()
            .Select(jp => new JObject(
                    new JProperty((string)jp.Value["type"], jp.Name),
                    new JProperty("attributes", jp.Value["attributes"])
                )
            )
        )
    )
);

json = newObj.ToString();

正在运行的演示:https://dotnetfiddle.net/zSWAL0

答案 1 :(得分:1)

这只是使用jsonata(https://www.nuget.org/packages/Retyped.jsonata)的另一种解决方案

因此表达式将是:

{
    "name": "NEW JSON",
    "company": $each($.component, function($v, $k){
    {"Person": "new-person",
    "attributes": {
            "Hair-color": $v.attributes.`Hair-color`,
                "Eye-color": $v.attributes.`Eye-color`,
                "employed": $v.status.employed,
                "ethnic": $v.status.ethnic
        }
    }
    })
}

实时演示:https://try.jsonata.org/6fpDBlo94