1 using Newtonsoft.Json; 2 using System; 3 using System.Collections.Generic; 4 using System.IO; 5 using System.Text.Json.Serialization; 6 7 namespace TestJSON 8 { 9 internal class Program 10 { 11 static void Main(string[] args) 12 { 13 Console.WriteLine("读取 data.json"); 14 string jsonString = File.ReadAllText("data.json"); 15 List<Item> myList = JsonConvert.DeserializeObject<List<Item>>(jsonString); 16 if (myList == null) 17 { 18 myList = new List<Item>(); 19 } 20 string input = "0"; 21 int inputInt = 0; 22 string inputString = ""; 23 while (input != "q") 24 { 25 Console.WriteLine("按'a'加项"); 26 Console.WriteLine("按'd'加项"); 27 Console.WriteLine("按's'加项"); 28 Console.WriteLine("按'q'加项"); 29 Console.WriteLine("按空格:"); 30 input = Console.ReadLine().ToLower(); 31 switch (input) 32 { 33 case "a": 34 Console.WriteLine("新加一项"); 35 Console.WriteLine("输入要增加名字:"); 36 inputString = Console.ReadLine(); 37 Console.WriteLine("请输入价格"); 38 inputInt = Convert.ToInt32(Console.ReadLine()); 39 myList.Add(new Item(inputString, inputInt)); 40 Console.WriteLine("新增加"+inputString+"价格"+inputInt); 41 break; 42 case "d": 43 Console.WriteLine("删除一项"); 44 Console.WriteLine("输入要删除名字:"); 45 inputString = Console.ReadLine(); 46 myList.Remove(new Item(inputString)); 47 break; 48 case "s": 49 Console.WriteLine("\n 显示每项"); 50 foreach (var item in myList) 51 { 52 Console.WriteLine("Item:"+item.Name+"|$"+item.Price); 53 } 54 Console.WriteLine("\n"); 55 break; 56 case "q": 57 Console.WriteLine("退出"); 58 break; 59 default: 60 Console.WriteLine("重新测试"); 61 break; 62 } 63 } 64 Console.WriteLine("开始写入 data.Json"); 65 string data= JsonConvert.SerializeObject(myList); 66 File.WriteAllText("data.json",data); 67 Console.WriteLine("写入完成"); 68 } 69 } 70 }
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Text; namespace TestJSON { public class Item : IEquatable<Item> { public string Name; public int Price; public Item(string name, int price =0) { this.Name = name; this.Price = price; } public bool Equals(Item other) { if (other == null) return false; return Name.Equals(other.Name); } } }
[{"Name":"ham","Price":1000000},{"Name":"huotuo","Price":20},{"Name":"xiao","Price":1},{"Name":"binggan","Price":12}]
标签:Console,测试,C#,System,myList,JSON,WriteLine,using,Name From: https://www.cnblogs.com/ZhongXingxing/p/17340706.html