In a file path I have a few json files and I’m trying to consolidate them into one file using C# newtonsoft json.
JSON1:
[{
"name": "name1",
"salary": 65000
}, {
"name": "name2",
"salary": 68000
}
]
JSON2:
[{
"name": "name3",
"salary": 56000
}, {
"name": "name4",
"salary": 58000
}
]
JSON3:
[{
"name": "name5",
"salary": 76000
}, {
"name": "name6",
"salary": 78000
}
]
JSON4:
[{
"name": "name7",
"salary": 86000
}, {
"name": "name8",
"salary": 88000
}
]
When I use the below code in C# I get the resulting file like below.
Code:
// 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:filePathnew.json";
File.WriteAllText(combinedJsonFilePath, combinedJson);
Result:
[
[{
"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
}
]
]
But, When the multiple json files are consolidated I want the file to look like below.
Desired Result:
[{
"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
Answers
Try working with collection of
JObject
‘s:Otherwise serializer will procees the whole JSON tree as a new element of the resulting collection (as you see in the resulting output).
@GuruStron’s answer is correct.
Another approach is you can read each JSON file and convert it as
JArray
(JArray.Parse(jsonContent)
) and combine theJArray
s into a single array viaJArray.Merge()
.