In a file path, I have a few JSON files and I'm trying to consolidate them into one file using 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, 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:\filePath\new.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 the 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
}
]
Try working with collection of JObject
's:
List<JObject> combinedJsonObjects = new List<JObject>();
// Load and append the JSON files
foreach (string filePath in jsonFilePaths)
{
string jsonContent = File.ReadAllText(filePath);
object jsonObject = JsonConvert.DeserializeObject<JObject[]>(jsonContent);
combinedJsonObjects.AddRange(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);
Otherwise serializer will procees the whole JSON tree as a new element of the resulting collection (as you see in the resulting output).