繁体   English   中英

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

[英]Transforming JSON from one structure to another

我有一个场景,我正在尝试解决问题。 我有一些 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 结构?

如果您只想转换 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

这只是使用 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM