Append data in a json file in C#

前端 未结 3 2017
庸人自扰
庸人自扰 2020-12-07 02:51

How would i keep appending data? I have this:

{
  \"13232\": [
    \"2012952\"
  ]
}

And i want to add an another object to it, example:

相关标签:
3条回答
  • 2020-12-07 02:56

    I recommand you use Newtonsoft Json lib, available as a nuget package.

    You can the make a model class to represent on of the json node then you can de-serialize you Json to that model and build an array containing the new element at the end to then re-serialize it to json after.

    Look at this MSDN page about it: https://msdn.microsoft.com/en-us/library/bb412179(v=vs.110).aspx

    Edit: Actual NewtonSoft Documentation

    In steps: 1 Deserialize the collection

    2: And a new class instance with listName.Add(className);

    3: Reserialize the collection

    0 讨论(0)
  • 2020-12-07 02:57

    The safest approach is read-update-rewrite (applies to JSON and XML format as they don't support appending).

    Next option if you can live with invalid JSON is to simply concatenate JSON fragments with code you have and than use SupportMultipleContent in JsonReader to read fragments Read Multiple Fragments With JsonReader

    If those approaches don't work and your format is fixed - find position of last ] in the file, seek stream there and write new array elements and append ]}.

    0 讨论(0)
  • 2020-12-07 03:04

    You won't be able to use file append operations to do this. File append operations can only add text to the end, they can't insert text at some point in the middle. This makes it impossible to use file-append to keep the JSON valid.

    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)
    2. 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)
    0 讨论(0)
提交回复
热议问题