在文件路径中,我有几个JSON文件,我试图使用Newtonsoft.JSON将它们合并到一个文件中。
JSON 1:
[
{
"name": "name1",
"salary": 65000
},
{
"name": "name2",
"salary": 68000
}
]
字符串
JSON 2:
[
{
"name": "name3",
"salary": 56000
},
{
"name": "name4",
"salary": 58000
}
]
型
JSON3:
[
{
"name": "name5",
"salary": 76000
},
{
"name": "name6",
"salary": 78000
}
]
型
JSON 4:
[
{
"name": "name7",
"salary": 86000
},
{
"name": "name8",
"salary": 88000
}
]
型
当我使用下面的代码时,我得到了如下所示的结果文件。
代码:
// List to store all the json objects
List<object> combinedJsonObjects = new List<object>();
// Load and append the JSON files
foreach (string filePath in jsonFilePaths)
{
string jsonContent = File.ReadAllText(filePath);
object jsonObject = JsonConvert.DeserializeObject(jsonContent);
combinedJsonObjects.Add(jsonObject);
}
// Serialize the appended JSON objects
string combinedJson = JsonConvert.SerializeObject(combinedJsonObjects, Newtonsoft.Json.Formatting.Indented);
// save JSON file
string combinedJsonFilePath = @"C:\filePath\new.json";
File.WriteAllText(combinedJsonFilePath, combinedJson);
型
测试结果:
[
[
{
"name": "name1",
"salary": 65000
},
{
"name": "name2",
"salary": 68000
}
],
[
{
"name": "name3",
"salary": 56000
},
{
"name": "name4",
"salary": 58000
}
],
[
{
"name": "name5",
"salary": 76000
},
{
"name": "name6",
"salary": 78000
}
],
[
{
"name": "name7",
"salary": 86000
},
{
"name": "name8",
"salary": 88000
}
]
]
型
但是,当多个JSON文件合并时,我希望文件看起来像下面这样。
预期结果:
[
{
"name": "name1",
"salary": 65000
},
{
"name": "name2",
"salary": 68000
},
{
"name": "name3",
"salary": 56000
},
{
"name": "name4",
"salary": 58000
},
{
"name": "name5",
"salary": 76000
},
{
"name": "name6",
"salary": 78000
},
{
"name": "name7",
"salary": 86000
},
{
"name": "name8",
"salary": 88000
}
]
型
2条答案
按热度按时间eyh26e7m1#
尝试使用
JObject
的集合:字符串
否则,序列化器将把整个JSON树作为结果集合的一个新元素进行处理(如结果输出中所示)。
wztqucjr2#
@GuruStron的回答是正确的。
另一种方法是读取每个JSON文件并将其转换为
JArray
(JArray.Parse(jsonContent)
),然后通过JArray.Merge()
将JArray
合并成一个数组。字符串