下载地址: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类
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace ConsoleApplication1
{
class Product
{
public string Name { get; set; } public decimal Price; public string[] Size { get; set; }
}
}
使用方式:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq; namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Product product = new Product()
{
Name = "Apple",
Price = 4.2M,
Size = new string[] {"Small","Medium","Large"}
};
//将对象转化成JSON字符串
string output = JsonConvert.SerializeObject(product);
Console.WriteLine(output);
//将JSON字符串转化成对象
Product product2 = JsonConvert.DeserializeObject<Product>(output);
Console.WriteLine(product2);
Console.WriteLine(product2.Name);
Console.ReadLine();
}
}
}
输出结果: