将来自的JSON字符串列表结果合并为具有一个根的单个JSON



我有一个列表JSON字符串,我想将它们合并到一个JSON数组中。

我正在从API获得一个结果,需要迭代结果字符串以获得一个单独的结果字符串

我有一个列表字符串,我需要迭代它,并将列表字符串转换为一个具有一个根元素的单个字符串,结果与合并

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
namespace ConsoleApp5
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
MergeJsonResult();
}
private static void MergeJsonResult()
{
List<string> jsonResult = new List<string>();
jsonResult.Add("{n  "arrayResult": [n    {"Item1": "123",n    "Item2": "858",n    "Item3": "789"n    },n    {"Item1": "2588",n    "Item2": "858",n    "Item3": "587"n    }n  ]n}");
jsonResult.Add("{n  "arrayResult": [n    {"Item1": "123",n    "Item2": "858",n    "Item3": "789"n    },n    {"Item1": "2588",n    "Item2": "858",n    "Item3": "587"n    }n  ]n}");
jsonResult.Add("{n  "arrayResult": [n    {"Item1": "123",n    "Item2": "858",n    "Item3": "789"n    },n    {"Item1": "2588",n    "Item2": "858",n    "Item3": "587"n    }n  ]n}");
foreach (var eachJson in jsonResult)
{
//Wat to merge JSON string
}
//Result should be with one root "arrayResult" and with in that the result array merged
}
}
}
**Result**
*Input*
- String1
{
"arrayResult": [
{
"Item1": "123",
"Item2": "858",
"Item3": "789"
},
{
"Item1": "2588",
"Item2": "858",
"Item3": "587"
}
]
}
- String2
{
"arrayResult": [
{
"Item1": "123",
"Item2": "858",
"Item3": "789"
},
{
"Item1": "2588",
"Item2": "858",
"Item3": "587"
}
]
}
- String3
{
"arrayResult": [
{
"Item1": "123",
"Item2": "858",
"Item3": "789"
},
{
"Item1": "2588",
"Item2": "858",
"Item3": "587"
}
]
}
*Output*
- Merged string with one root 
{
"arrayResult": [
{
"Item1": "123",
"Item2": "858",
"Item3": "789"
},
{
"Item1": "2588",
"Item2": "858",
"Item3": "587"
},
{
"Item1": "123",
"Item2": "858",
"Item3": "789"
},
{
"Item1": "2588",
"Item2": "858",
"Item3": "587"
},
{
"Item1": "123",
"Item2": "858",
"Item3": "789"
},
{
"Item1": "2588",
"Item2": "858",
"Item3": "587"
}
]
}

解决方案1:LINQ方法

  1. jsonResult列表中,将每个项(JSON字符串(解析为JObject

  2. 从结果1中,提取arrayResult的值作为JToken。它将arrayResult数组中的项返回为List<JToken>

  3. 创建一个具有arrayResult属性的对象,该对象保存2的结果。

using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
List<JToken> items = jsonResult.Select(x => JObject.Parse(x))
.SelectMany(x => x["arrayResult"])
.ToList();

dynamic result = new {
arrayResult = items 
};

演示解决方案1@.NET Fiddle


解决方案2:foreach循环方法

  1. 创建一个具有arrayResult属性的对象,该属性包含数组。

  2. jsonResult中的每个元素进行迭代,将JSON字符串解析为JObject,从JObject中提取arrayResult值。这将返回项目列表。然后您需要使用.AddRange()将项目列表添加到result.arrayResult

dynamic result = new {
arrayResult = new List<dynamic>()   
};

foreach (var eachJson in jsonResult)
{
result.arrayResult.AddRange(JObject.Parse(eachJson)
.SelectToken("arrayResult")
.ToList());
}

演示解决方案2@.NET Fiddle

最新更新