核心功能
1. 基础序列化/反序列化
JsonConvert.SerializeObject()
– 对象转JSONJsonConvert.DeserializeObject<T>()
– JSON转对象
2. 属性控制
[JsonProperty]
– 自定义属性名[JsonIgnore]
– 忽略属性[JsonConverter]
– 自定义转换器
3. 格式化选项
Formatting.Indented
– 格式化输出NullValueHandling
– 空值处理DefaultValueHandling
– 默认值处理
4. 动态操作
JObject
– 动态创建和修改JSONJArray
– JSON数组操作- LINQ to JSON – 使用LINQ查询JSON
5. 高级特性
- 自定义JsonConverter
- 错误处理机制
- 性能优化设置
- 驼峰命名转换
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
// 1. 基本模型定义
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public string Email { get; set; }
public DateTime BirthDate { get; set; }
public List<string> Hobbies { get; set; } = new List<string>();
}
// 2. 带属性配置的复杂模型
public class Product
{
[JsonProperty("product_id")]
public int Id { get; set; }
[JsonProperty("product_name")]
public string Name { get; set; }
[JsonProperty("unit_price")]
public decimal Price { get; set; }
[JsonProperty("created_date")]
[JsonConverter(typeof(IsoDateTimeConverter))]
public DateTime CreatedDate { get; set; }
[JsonProperty("is_active")]
public bool IsActive { get; set; }
// 忽略序列化
[JsonIgnore]
public string InternalNotes { get; set; }
// 条件序列化
[JsonProperty("description")]
public string Description { get; set; }
public bool ShouldSerializeDescription()
{
return !string.IsNullOrEmpty(Description);
}
}
// 3. 嵌套对象模型
public class Order
{
public int OrderId { get; set; }
public Person Customer { get; set; }
public List<OrderItem> Items { get; set; } = new List<OrderItem>();
public decimal TotalAmount { get; set; }
public OrderStatus Status { get; set; }
}
public class OrderItem
{
public Product Product { get; set; }
public int Quantity { get; set; }
public decimal UnitPrice { get; set; }
}
public enum OrderStatus
{
Pending,
Processing,
Shipped,
Delivered,
Cancelled
}
public class NewtonsoftJsonExamples
{
public static void RunAllExamples()
{
Console.WriteLine("=== Newtonsoft.Json 使用案例 ===\n");
BasicSerializationExample();
BasicDeserializationExample();
JsonPropertyAttributeExample();
JsonIgnoreExample();
DateTimeHandlingExample();
EnumHandlingExample();
CustomSerializationExample();
JObjectDynamicExample();
LinqToJsonExample();
ErrorHandlingExample();
PerformanceOptimizationExample();
JsonConverterExample();
NullValueHandlingExample();
CamelCaseExample();
}
// 1. 基础序列化
public static void BasicSerializationExample()
{
Console.WriteLine("1. 基础序列化示例:");
var person = new Person
{
Name = "张三",
Age = 30,
Email = "zhangsan@example.com",
BirthDate = new DateTime(1993, 5, 15),
Hobbies = new List<string> { "阅读", "游泳", "编程" }
};
// 基本序列化
string json = JsonConvert.SerializeObject(person);
Console.WriteLine($"基本序列化: {json}");
// 格式化输出
string formattedJson = JsonConvert.SerializeObject(person, Formatting.Indented);
Console.WriteLine($"格式化输出:\n{formattedJson}");
Console.WriteLine();
}
// 2. 基础反序列化
public static void BasicDeserializationExample()
{
Console.WriteLine("2. 基础反序列化示例:");
string json = @"{
'Name': '李四',
'Age': 25,
'Email': 'lisi@example.com',
'BirthDate': '1998-08-20T00:00:00',
'Hobbies': ['音乐', '旅行']
}";
try
{
var person = JsonConvert.DeserializeObject<Person>(json);
Console.WriteLine($"姓名: {person.Name}");
Console.WriteLine($"年龄: {person.Age}");
Console.WriteLine($"邮箱: {person.Email}");
Console.WriteLine($"爱好: {string.Join(", ", person.Hobbies)}");
}
catch (JsonException ex)
{
Console.WriteLine($"反序列化错误: {ex.Message}");
}
Console.WriteLine();
}
// 3. JsonProperty 属性使用
public static void JsonPropertyAttributeExample()
{
Console.WriteLine("3. JsonProperty 属性示例:");
var product = new Product
{
Id = 1001,
Name = "iPhone 15",
Price = 6999.99m,
CreatedDate = DateTime.Now,
IsActive = true,
Description = "最新款iPhone",
InternalNotes = "内部备注"
};
string json = JsonConvert.SerializeObject(product, Formatting.Indented);
Console.WriteLine($"产品信息:\n{json}");
// 反序列化
var deserializedProduct = JsonConvert.DeserializeObject<Product>(json);
Console.WriteLine($"反序列化后: {deserializedProduct.Name} - ¥{deserializedProduct.Price}");
Console.WriteLine();
}
// 4. JsonIgnore 使用
public static void JsonIgnoreExample()
{
Console.WriteLine("4. JsonIgnore 示例:");
var product = new Product
{
Id = 1002,
Name = "MacBook Pro",
Price = 12999.99m,
CreatedDate = DateTime.Now,
IsActive = true,
InternalNotes = "这个字段不会被序列化"
};
string json = JsonConvert.SerializeObject(product, Formatting.Indented);
Console.WriteLine($"注意 InternalNotes 字段被忽略:\n{json}");
Console.WriteLine();
}
// 5. 日期时间处理
public static void DateTimeHandlingExample()
{
Console.WriteLine("5. 日期时间处理示例:");
var data = new
{
CurrentTime = DateTime.Now,
UtcTime = DateTime.UtcNow,
SpecificDate = new DateTime(2024, 1, 1, 12, 0, 0)
};
// 默认格式
var settings1 = new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.IsoDateFormat
};
string json1 = JsonConvert.SerializeObject(data, Formatting.Indented, settings1);
Console.WriteLine($"ISO 格式:\n{json1}");
// 自定义格式
var settings2 = new JsonSerializerSettings
{
DateFormatString = "yyyy-MM-dd HH:mm:ss"
};
string json2 = JsonConvert.SerializeObject(data, Formatting.Indented, settings2);
Console.WriteLine($"自定义格式:\n{json2}");
Console.WriteLine();
}
// 6. 枚举处理
public static void EnumHandlingExample()
{
Console.WriteLine("6. 枚举处理示例:");
var order = new Order
{
OrderId = 12345,
Status = OrderStatus.Processing,
TotalAmount = 299.99m
};
// 默认 - 数字
string json1 = JsonConvert.SerializeObject(order, Formatting.Indented);
Console.WriteLine($"默认(数字):\n{json1}");
// 字符串格式
var settings = new JsonSerializerSettings();
settings.Converters.Add(new StringEnumConverter());
string json2 = JsonConvert.SerializeObject(order, Formatting.Indented, settings);
Console.WriteLine($"字符串格式:\n{json2}");
Console.WriteLine();
}
// 7. 自定义序列化设置
public static void CustomSerializationExample()
{
Console.WriteLine("7. 自定义序列化设置示例:");
var person = new Person
{
Name = "王五",
Age = 0, // 默认值
Email = null // null值
};
var settings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
DefaultValueHandling = DefaultValueHandling.Ignore,
ContractResolver = new CamelCasePropertyNamesContractResolver(),
Formatting = Formatting.Indented
};
string json = JsonConvert.SerializeObject(person, settings);
Console.WriteLine($"自定义设置:\n{json}");
Console.WriteLine();
}
// 8. JObject 动态操作
public static void JObjectDynamicExample()
{
Console.WriteLine("8. JObject 动态操作示例:");
// 创建 JObject
var jobject = new JObject
{
["name"] = "赵六",
["age"] = 28,
["skills"] = new JArray { "C#", "JavaScript", "Python" },
["address"] = new JObject
{
["city"] = "北京",
["district"] = "朝阳区"
}
};
Console.WriteLine($"JObject 创建:\n{jobject.ToString(Formatting.Indented)}");
// 动态修改
jobject["age"] = 29;
jobject["skills"].First.AddAfterSelf("Java");
Console.WriteLine($"修改后:\n{jobject.ToString(Formatting.Indented)}");
// 访问属性
Console.WriteLine($"姓名: {jobject["name"]}");
Console.WriteLine($"城市: {jobject["address"]["city"]}");
Console.WriteLine();
}
// 9. LINQ to JSON
public static void LinqToJsonExample()
{
Console.WriteLine("9. LINQ to JSON 示例:");
string json = @"[
{'name': '张三', 'age': 30, 'department': 'IT'},
{'name': '李四', 'age': 25, 'department': 'HR'},
{'name': '王五', 'age': 35, 'department': 'IT'},
{'name': '赵六', 'age': 28, 'department': 'Finance'}
]";
JArray employees = JArray.Parse(json);
// LINQ 查询
var itEmployees = employees
.Where(e => e["department"].ToString() == "IT")
.Select(e => new {
Name = e["name"].ToString(),
Age = (int)e["age"]
});
Console.WriteLine("IT部门员工:");
foreach (var emp in itEmployees)
{
Console.WriteLine($" {emp.Name}, {emp.Age}岁");
}
// 统计
var avgAge = employees.Average(e => (int)e["age"]);
Console.WriteLine($"平均年龄: {avgAge:F1}");
Console.WriteLine();
}
// 10. 错误处理
public static void ErrorHandlingExample()
{
Console.WriteLine("10. 错误处理示例:");
string invalidJson = "{ 'name': 'test', 'age': 'invalid_number' }";
var settings = new JsonSerializerSettings
{
Error = (sender, args) =>
{
Console.WriteLine($"序列化错误: {args.ErrorContext.Error.Message}");
Console.WriteLine($"路径: {args.ErrorContext.Path}");
args.ErrorContext.Handled = true;
}
};
try
{
var person = JsonConvert.DeserializeObject<Person>(invalidJson, settings);
Console.WriteLine($"处理后: {person?.Name}, Age: {person?.Age}");
}
catch (Exception ex)
{
Console.WriteLine($"未处理的异常: {ex.Message}");
}
Console.WriteLine();
}
// 11. 性能优化
public static void PerformanceOptimizationExample()
{
Console.WriteLine("11. 性能优化示例:");
var people = Enumerable.Range(1, 1000)
.Select(i => new Person
{
Name = $"Person{i}",
Age = 20 + (i % 50),
Email = $"person{i}@example.com"
})
.ToList();
var stopwatch = System.Diagnostics.Stopwatch.StartNew();
// 使用预配置的设置
var settings = new JsonSerializerSettings
{
ContractResolver = new DefaultContractResolver(),
DateFormatHandling = DateFormatHandling.IsoDateFormat
};
string json = JsonConvert.SerializeObject(people, settings);
stopwatch.Stop();
Console.WriteLine($"序列化 {people.Count} 个对象耗时: {stopwatch.ElapsedMilliseconds}ms");
Console.WriteLine($"JSON 长度: {json.Length} 字符");
Console.WriteLine();
}
// 12. 自定义 JsonConverter
public static void JsonConverterExample()
{
Console.WriteLine("12. 自定义 JsonConverter 示例:");
var person = new Person
{
Name = "自定义转换器测试",
Age = 30,
BirthDate = DateTime.Now
};
var settings = new JsonSerializerSettings();
settings.Converters.Add(new CustomDateTimeConverter());
string json = JsonConvert.SerializeObject(person, Formatting.Indented, settings);
Console.WriteLine($"使用自定义转换器:\n{json}");
Console.WriteLine();
}
// 13. 空值处理
public static void NullValueHandlingExample()
{
Console.WriteLine("13. 空值处理示例:");
var person = new Person
{
Name = "测试用户",
Email = null,
Hobbies = null
};
// 包含空值
var includeNulls = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Include,
Formatting = Formatting.Indented
};
// 忽略空值
var ignoreNulls = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
Formatting = Formatting.Indented
};
Console.WriteLine("包含空值:");
Console.WriteLine(JsonConvert.SerializeObject(person, includeNulls));
Console.WriteLine("忽略空值:");
Console.WriteLine(JsonConvert.SerializeObject(person, ignoreNulls));
Console.WriteLine();
}
// 14. 驼峰命名
public static void CamelCaseExample()
{
Console.WriteLine("14. 驼峰命名示例:");
var product = new Product
{
Id = 1,
Name = "测试产品",
Price = 99.99m,
IsActive = true
};
var camelCaseSettings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
Formatting = Formatting.Indented
};
string json = JsonConvert.SerializeObject(product, camelCaseSettings);
Console.WriteLine($"驼峰命名:\n{json}");
Console.WriteLine();
}
}
// 自定义 DateTime 转换器
public class CustomDateTimeConverter : JsonConverter<DateTime>
{
public override void WriteJson(JsonWriter writer, DateTime value, JsonSerializer serializer)
{
writer.WriteValue(value.ToString("yyyy年MM月dd日 HH:mm:ss"));
}
public override DateTime ReadJson(JsonReader reader, Type objectType, DateTime existingValue, bool hasExistingValue, JsonSerializer serializer)
{
string dateString = (string)reader.Value;
if (DateTime.TryParse(dateString, out DateTime result))
{
return result;
}
return DateTime.MinValue;
}
}
// 程序入口点示例
public class Program
{
public static void Main(string[] args)
{
NewtonsoftJsonExamples.RunAllExamples();
Console.WriteLine("按任意键退出...");
Console.ReadKey();
}
}