1

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

2
  • 1
    Just in case it's really sensitive data, a small hint: The blurred URL is still readable. Commented Jul 24, 2018 at 6:35
  • 2
    When did screenshoot + crop + edit a blur became faster that copy past and deleted the string you needed to? Commented Jul 24, 2018 at 6:42

2 Answers 2

3

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)
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.