C# 中,对象转JSON以及对象转JSON字符串或者反向转换
对象转JSON:
1 private void button3_Click(object sender, EventArgs e) 2 { 3 SaleOrder_Save_Main.Main SM = new SaleOrder_Save_Main.Main(); 4 SM.csocode = "000001"; 5 SM.id = 100; 6 7 JObject JO = new JObject(); 8 9 JsonSerializer JZ = new JsonSerializer(); 10 JZ.NullValueHandling = NullValueHandling.Ignore; 11 12 JO = JObject.FromObject(SM, JZ); 13 14 SaleOrder_Save_Detail.Detail SD = new SaleOrder_Save_Detail.Detail(); 15 JArray JA = new JArray(); 16 { 17 JObject JO1 = new JObject(); 18 SD.cinvcode = "1000"; 19 SD.autoid = 1234; 20 SD.fsaleprice = (decimal?)12.5; 21 JO1 = JObject.FromObject(SD, JZ); 22 JA.Add(JO1); 23 JO1 = new JObject(); 24 SD.cinvcode = "1200"; 25 SD.autoid = 1235; 26 SD.fsaleprice = (decimal?)8.7; 27 JO1 = JObject.FromObject(SD, JZ); 28 JA.Add(JO1); 29 } 30 JO.Add("details", JA); 31 textBox1.Text= JsonConvert.SerializeObject(JO, Newtonsoft.Json.Formatting.Indented); 32 }
Json字符串转对象:
1 private void button4_Click(object sender, EventArgs e) 2 { 3 JObject JO = (JObject)JsonConvert.DeserializeObject(textBox1.Text); 4 SaleOrder_Save_Main.Main SM = new SaleOrder_Save_Main.Main(); 5 SM = JsonConvert.DeserializeObject<SaleOrder_Save_Main.Main>(textBox1.Text); 6 string json = JsonConvert.SerializeObject(JO["details"]); 7 List<SaleOrder_Save_Detail.Detail> Details = JsonConvert.DeserializeObject<List<SaleOrder_Save_Detail.Detail>>(json); 8 textBox2.AppendText(Details[0].autoid.ToString()); 9 }