Tixart
Tixart

Reputation: 23

C#: Appending Json Object to a Json file already containing data

I have created an object which contains data I want to insert/append to the data currently sitting in a json file. I have succeeded in getting to to write the data to the file however it overwrites all the data that was there originally. What i am trying to do is append this Property to the json file whilst keeping all the original information.

This is what I have done so far:

string widthBox = Width.Text.ToString();
string heightBox = Height.Text.ToString();

string WindowSizejson = File.ReadAllText(DownloadConfigFilelocation);
dynamic WindowSizejsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject(WindowSizejson);
JObject windowContent = new JObject(
    new JProperty("externalSite",
        new JObject(
            new JProperty("webLogin",
                new JObject(
                    new JProperty("window", "height=" + heightBox + ",width=" + widthBox + ",resizable,scrollbars")
                )
            )
        )
    )
);

This is the data currently in the json file that i need to append the above to. ( have blurred out values due to company security reasons)

SEE IMAGE HERE

Upvotes: 0

Views: 1179

Answers (2)

Hossein
Hossein

Reputation: 3113

You have two choices that I can think of:

1.Read the entire file into an object, add your object, and then rewrite the entire file (poor performance)

var filePath = @"path.json";
// Read existing json data
var jsonData = System.IO.File.ReadAllText(filePath);
// De-serialize to object or create new list
var SomeObjectList= JsonConvert.DeserializeObject<List<T>>(jsonData) 
                      ?? new List<T>();

// Add any new 
SomeObjectList.Add(new T()
{
    Name = "..."
});
SomeObjectList.Add(new T()
{
    Name = "..."
});

// edit 
var first = SomeObjectList.FirstOrDefault();
first.Name = "...";


// Update json data string
jsonData = JsonConvert.SerializeObject(SomeObjectList);
System.IO.File.WriteAllText(filePath, jsonData);
  1. Open the file read/write, parse through until you get to the closing curly brace, then write the remaining data, then write the close curly brace (not trivial)

Upvotes: 3

Barr J
Barr J

Reputation: 10927

Instead of messing around with JProperty, deserialize your json and append your desired data:

JObject obj = JObject.Parse(jsontext);
obj["new_prop"] = "value";//new property as per hirarchy ,same for replacing values
string newjson=obj.ToString();

it's much cleaner and easier to maintain.

Upvotes: 0

Related Questions