You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从前端编辑控件返回的JArray对象中提取并拼接所有text值

提取并拼接JArray中的所有"text"值

需求说明

从前端编辑控件返回的JArray对象中,检索所有层级的"text"字段值,拼接成一个完整字符串,示例理想结果:

"Established in 1995, the Elephant Sanctuary in Tennessee has provided ...spans 2,700 acres. This is underlined text. This is italic text. This is bold text"

解决方案(C#)

使用Newtonsoft.Json处理JArray,遍历提取目标文本:

using Newtonsoft.Json.Linq;
using System.Text;

public string CombineAllTextFromJArray(JArray contentArray)
{
    var combinedText = new StringBuilder();

    foreach (var paragraph in contentArray)
    {
        // 跳过无内容的段落
        var contentItems = paragraph["content"];
        if (contentItems == null || !contentItems.HasValues)
            continue;

        // 遍历段落内的文本项
        foreach (var item in contentItems)
        {
            if (item["type"]?.Value<string>() == "text")
            {
                string text = item["text"]?.Value<string>();
                if (!string.IsNullOrWhiteSpace(text))
                {
                    combinedText.Append(text);
                }
            }
        }
    }

    return combinedText.ToString();
}

代码说明

  1. 遍历JArray中的每个段落对象
  2. 跳过没有content字段或content为空的段落
  3. 筛选type为text的内容项,提取其text值
  4. 用StringBuilder拼接所有非空文本,避免频繁字符串拼接的性能损耗

测试结果

将你提供的JArray传入上述方法,会直接输出你期望的拼接字符串。

内容的提问来源于stack exchange,提问作者mrhusky

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 12:22:43