json JArray -从特定参数获取所有值

n9vozmp4  于 2023-03-09  发布在  其他
关注(0)|答案(2)|浏览(185)

我从前端编辑控件接收到一个JArray对象。我想检索并连接所有“文本”值。
理想的结果应该是一个字符串:
田纳西州的大象保护区成立于1995年,占地2,700英亩。这是下划线文本,这是斜体文本,这是粗体文本

[
  {
    "type": "paragraph",
    "attrs": {
      "style": null,
      "class": null,
      "id": null
    },
    "content": [
      {
        "type": "text",
        "text": "Established in 1995, the Elephant Sanctuary in Tennessee has provided ..."
      },
      {
        "type": "text",
        "marks": [
          {
            "type": "strong"
          }
        ],
        "text": "spans 2,700 acres."
      }
    ]
  },
  {
    "type": "paragraph",
    "attrs": {
      "style": null,
      "class": null,
      "id": null
    }
  },
  {
    "type": "paragraph",
    "attrs": {
      "style": null,
      "class": null,
      "id": null
    },
    "content": [
      {
        "type": "text",
        "marks": [
          {
            "type": "u"
          }
        ],
        "text": "This is underlined text."
      }
    ]
  },
  {
    "type": "paragraph",
    "attrs": {
      "style": null,
      "class": null,
      "id": null
    },
    "content": [
      {
        "type": "text",
        "marks": [
          {
            "type": "em"
          }
        ],
        "text": "This is italic text."
      }
    ]
  },
  {
    "type": "paragraph",
    "attrs": {
      "style": null,
      "class": null,
      "id": null
    },
    "content": [
      {
        "type": "text",
        "marks": [
          {
            "type": "strong"
          }
        ],
        "text": "This is bold text"
      }
    ]
  }
]
ej83mcc0

ej83mcc01#

您可以使用JSONPath

var jArray = JArray.Parse(json);

var s = string.Join(".", jArray.SelectTokens("$..text"));

下面列出了可以使用表达式。

uajslkp6

uajslkp62#

你可以试试这个

string text = string.Join(" ", JArray.Parse(json).Where(j => j["content"] != null)
                    .SelectMany(j => j["content"].Select(i => (string) i["text"])));

相关问题