json add new object to existing json file C#

后端 未结 4 1098
旧巷少年郎
旧巷少年郎 2020-12-10 06:34

I\'m trying to automate the adding of new objects to an existing json file. I looked all around the web but only found adding data and stuff but not an whole object. This is

相关标签:
4条回答
  • 2020-12-10 07:02

    A better performing solution than serializing/deserializing what may be a large file would be to open a FileStream, seek 1 character before the end, then serialize and write your new object into the array, then write a closing bracket. See this question C# How to delete last 2 characters from text file and write into the same line at the end my text?, I'll copy the code here - you already know how to serialize your object and encode it into bytes.

    using(var fs = new FileStream("file.json")) {    
        fs.Seek(-1,SeekOrigin.End);        
        fs.Write(mySerializedJSONObjAsBytes,0,mySerializedJSONObjAsBytes.Length); // include a leading comma character if required
        fs.Write(squareBracketByte, 0, 1);
        fs.SetLength(fs.Position); //Only needed if new content may be smaller than old
    }
    

    Sorry haven't tested any of that, it's off the top of my head. Pro-tip: wrap FileStream in a StreamWriter so can write strings directly.

    0 讨论(0)
  • 2020-12-10 07:15

    Using Json.Net

    //load from file
    var initialJson = "[{\"id\":\"123\",\"name\":\"carl\"}]";
    
    var array = JArray.Parse(initialJson);
    
    var itemToAdd = new JObject();
    itemToAdd["id"] = 1234;
    itemToAdd["name"] = "carl2";
    array.Add(itemToAdd);
    
    var jsonToOutput = JsonConvert.SerializeObject(array, Formatting.Indented);
    
    //save to file here
    

    Using this method doesn't require strongly typed objects

    You could replace this bit:

    //load from file
    var initialJson = "[{\"id\":\"123\",\"name\":\"carl\"}]";
    

    With

    var initialJson = File.ReadAllText(@"c:\myjson.json")
    

    To load the json from a text file

    0 讨论(0)
  • 2020-12-10 07:18

    You could create a method:

    public string AddObjectsToJson<T>(string json, List<T> objects)
    {
        List<T> list = JsonConvert.DeserializeObject<List<T>>(json);
        list.AddRange(objects);
        return JsonConvert.SerializeObject(list);
    }
    

    Then use it like this:

    string baseJson = "[{\"id\":\"123\",\"name\":\"carl\"}]";
    List<Person> personsToAdd = new List<Person>() { new Person(1234,"carl2") };
    
    string updatedJson = AddObjectsToJson(baseJson, personsToAdd);
    
    0 讨论(0)
  • 2020-12-10 07:22

    If you use json.NET you can simply deserialize and serialize the json.

    var list = JsonConvert.DeserializeObject<List<Person>>(myJsonString);
    list.Add(new Person(1234,"carl2");
    var convertedJson = JsonConvert.SerializeObject(list, Formatting.Indented);
    
    0 讨论(0)
提交回复
热议问题