如何从前端编辑控件返回的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(); }
代码说明
- 遍历JArray中的每个段落对象
- 跳过没有
content字段或content为空的段落 - 筛选
type为text的内容项,提取其text值 - 用StringBuilder拼接所有非空文本,避免频繁字符串拼接的性能损耗
测试结果
将你提供的JArray传入上述方法,会直接输出你期望的拼接字符串。
内容的提问来源于stack exchange,提问作者mrhusky
相关产品推荐
相关产品推荐

