In the morning when you learn the Post model to Web API create or save data http://www.cnblogs.com/insus/p/4343833.html, if you add the second, the JSON file can only be a single record and the latest data.
How do you need to append the newly added JSON data to the existing data? This article insus.net is to implement this function.
The idea is to first read the JSON file into the data set in memory, the newly added data is appended, and then the memory data set is serialized into a JSON file.
In the above code example, there are 3 parts, the first part reads the original data from the file:
if (System.IO.File.Exists ( Existfilephysicalpath) { using (System.IO.StreamRea Der sr = new System.IO.StreamReader ( Existfilephysicalpath) {jsontextreader jtr = new< /span> JsonTextReader (SR); Jsonserializer se = new Jsonserializer () ; object obj = se. Deserialize (JTR, typeof (List<order> = (List<order>
View Code
In fact, this part, a simple code can also:
Orders = jsonconvert.deserializeobject<list<order>> (System.IO.File.ReadAllText (Existfilephysicalpath ));
View Code
The second part is to serialize the in-memory list<order> data and save it as a JSON file:
using (FileStream fs = File.Open (Newfilephysicalpath, filemode.createnew)) using New StreamWriter (FS)) using New JsonTextWriter (SW)) { = formatting.indented; New Jsonserializer (); Serializer. Serialize (JW, orders); }
View Code
The third part is to rename the newly created file to the old file name:
if (System.IO.File.Exists (existfilephysicalpath)) { file.delete (existfilephysicalpath); } if (System.IO.File.Exists (newfilephysicalpath)) { System.IO.File.Move (Newfilephysicalpath, Existfilephysicalpath); }
View Code
In the Orders directory, create a new HTML page savejsontoexistfile.html:
The above collection of jquery code, you can refer to the following:
Insus.net's practice, in general, is the end of an animated presentation:
Add JSON data to a JSON file that already exists