Writing multiple values to json file throws “only one top level item is allowed ” error C#

The issue is caused by adding a new json list to the file every time this method gets called.

What you want to do is first load the json list from this file into your csharp code, then add the new ServerToScreen object to the loaded list, and then replace the json file with the new list.

Code example:

ServerToScreen newObject = new ServerToScreen() {
// create the new ServerToScreen object with all properties

var serializer = new JavaScriptSerializer();
string outputPath = Server.MapPath("~/TvScreenData/") + "output.json";

// Load current list from the file
string currentList = System.IO.File.ReadAllText(outputPath);
List<ServerToScreen> screenData = serializer.Deserialize<List<ServerToScreen>>(currentList);

// Add the new object to this list

// Serialize the list including the new object, and replace the file
string jsonWithNewObject = serializer.Serialize(screenData);
System.IO.File.WriteAllText(outputPath, jsonWithNewObject);

Note: code is untested

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top