Add JSON Data to an existing JSON file.
In the morning, I learned the Post model to Web Api to create or save data http://www.cnblogs.com/insus/p/4343833.html. if you add a second, the data in the json file can only be a single record and up-to-date.
So how do I append the newly added json data to existing data? This article Insus. NET is intended to implement this function.
The idea is to first convert the data from the json file into a dataset and store it in the memory. Then add the newly added data and then serialize the memory dataset and save it as a json file.
In the code example above, there are three major parts. The first part is to read the original data in the file:
If (System. IO. file. exists (existFilePhysicalPath) {using (System. IO. streamReader sr = new System. IO. streamReader (existFilePhysicalPath) {JsonTextReader jtr = new JsonTextReader (sr); JsonSerializer se = new JsonSerializer (); object obj = se. deserialize (jtr, typeof (List <Order>); orders = (List <Order>) obj ;}}View Code
In fact, this part can also be a simple code:
Orders = JsonConvert. DeserializeObject <List <Order> (System. IO. File. ReadAllText (existFilePhysicalPath ));View Code
The second part is to serialize the List <Order> data in the memory and save it as a json file:
Using (FileStream fs = File. open (newFilePhysicalPath, FileMode. createNew) using (StreamWriter sw = new StreamWriter (fs) using (JsonWriter jw = new JsonTextWriter (sw) {jw. formatting = Formatting. indented; JsonSerializer serializer = 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 ordersdirectory, create a new HTML webpage savejsontoexistfile.html:
The jQuery code collected above can be referred to below:
The exercises done by Insus. NET are generally followed by an animated Demonstration: