JSON.NET 教程(一)

下载地址:http://www.newtonsoft.com/json

参考官网文档:http://www.newtonsoft.com/json/help/html/SerializingJSON.htm

使用前:请添加引用 NewTonsoft.Json程序集

 

一、JsonConver用于JSON字符串和对象之间的相互转换

  string SerializeObject(object):用于将对象转化成JSON格式的字符串

  T DeserializeObject<T>(string):用于将JSON格式的字符串转化成对象

  案例:

Product类

 1 using System.Collections.Generic;
 2 using System.Linq;
 3 using System.Text;
 4 using System.Threading.Tasks;
 5 
 6 namespace ConsoleApplication1
 7 {
 8     class Product
 9     {
10         public string Name { get; set; }
11 
12         public decimal Price;
13 
14         public string[] Size { get; set; }
15     }
16 }


使用方式:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 using Newtonsoft.Json;
 7 using Newtonsoft.Json.Linq;
 8 
 9 namespace ConsoleApplication1
10 {
11     class Program
12     {
13         static void Main(string[] args)
14         {
15             Product product = new Product()
16             {
17                 Name = "Apple",
18                 Price = 4.2M,
19                 Size = new string[] {"Small","Medium","Large"}
20             };
21             //将对象转化成JSON字符串
22             string output = JsonConvert.SerializeObject(product);
23             Console.WriteLine(output);
24             //将JSON字符串转化成对象
25             Product product2 = JsonConvert.DeserializeObject<Product>(output);
26             Console.WriteLine(product2);
27             Console.WriteLine(product2.Name);
28             Console.ReadLine();
29         }
30     }
31 }

输出结果:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值