.NET 對象轉(zhuǎn)Json的幾種常見方式
在.NET中將對象轉(zhuǎn)換為JSON有多種方法,以下是常用的幾種方式:
1. 使用 System.Text.Json (推薦,.NET Core 3.0+)
基本序列化
using System.Text.Json;
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public string Email { get; set; }
}
// 對象轉(zhuǎn)JSON
var person = new Person { Name = "張三", Age = 25, Email = "zhangsan@example.com" };
string jsonString = JsonSerializer.Serialize(person);
Console.WriteLine(jsonString);
// 輸出: {"Name":"張三","Age":25,"Email":"zhangsan@example.com"}
帶選項(xiàng)的序列化
var options = new JsonSerializerOptions
{
WriteIndented = true, // 格式化輸出
PropertyNamingPolicy = JsonNamingPolicy.CamelCase // 駝峰命名
};
string jsonString = JsonSerializer.Serialize(person, options);
Console.WriteLine(jsonString);
// 輸出:
// {
// "name": "張三",
// "age": 25,
// "email": "zhangsan@example.com"
// }
2. 使用 Newtonsoft.Json (Json.NET)
首先安裝 NuGet 包:
Install-Package Newtonsoft.Json
using Newtonsoft.Json;
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public string Email { get; set; }
}
// 基本序列化
var person = new Person { Name = "李四", Age = 30, Email = "lisi@example.com" };
string jsonString = JsonConvert.SerializeObject(person);
Console.WriteLine(jsonString);
// 帶格式的序列化
string formattedJson = JsonConvert.SerializeObject(person, Formatting.Indented);
Console.WriteLine(formattedJson);
Newtonsoft.Json 高級用法
var settings = new JsonSerializerSettings
{
Formatting = Formatting.Indented,
NullValueHandling = NullValueHandling.Ignore,
DateFormatString = "yyyy-MM-dd HH:mm:ss"
};
string jsonString = JsonConvert.SerializeObject(person, settings);
3. 處理復(fù)雜對象
包含集合的對象
public class Department
{
public string Name { get; set; }
public List<Person> Employees { get; set; }
}
var department = new Department
{
Name = "技術(shù)部",
Employees = new List<Person>
{
new Person { Name = "王五", Age = 28, Email = "wangwu@example.com" },
new Person { Name = "趙六", Age = 32, Email = "zhaoliu@example.com" }
}
};
string jsonString = JsonSerializer.Serialize(department, new JsonSerializerOptions { WriteIndented = true });
Console.WriteLine(jsonString);
匿名對象序列化
var anonymousObject = new
{
Id = 1,
Description = "測試對象",
CreateTime = DateTime.Now
};
string jsonString = JsonSerializer.Serialize(anonymousObject);
Console.WriteLine(jsonString);
4. 自定義序列化選項(xiàng)
System.Text.Json 自定義
var options = new JsonSerializerOptions
{
WriteIndented = true,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull,
Converters = { new JsonStringEnumConverter() } // 枚舉轉(zhuǎn)換為字符串
};
string jsonString = JsonSerializer.Serialize(person, options);
使用特性控制序列化
public class Product
{
[JsonPropertyName("productName")] // System.Text.Json
public string Name { get; set; }
[JsonIgnore] // 忽略該屬性
public string InternalCode { get; set; }
[JsonPropertyOrder(1)] // 屬性順序
public decimal Price { get; set; }
}
5. 性能優(yōu)化
使用源生成器 (System.Text.Json)
[JsonSerializable(typeof(Person))]
[JsonSerializable(typeof(List<Person>))]
public partial class MyJsonContext : JsonSerializerContext
{
}
// 使用源生成器進(jìn)行序列化
var person = new Person { Name = "測試", Age = 25 };
string jsonString = JsonSerializer.Serialize(person, MyJsonContext.Default.Person);
選擇建議
- 新項(xiàng)目:推薦使用
System.Text.Json,性能更好,無需額外依賴 - 現(xiàn)有項(xiàng)目:如果已經(jīng)在使用 Newtonsoft.Json,可以繼續(xù)使用
- 復(fù)雜場景:Newtonsoft.Json 功能更豐富,支持更多復(fù)雜場景
兩種方法都很常用,根據(jù)項(xiàng)目需求和個(gè)人偏好選擇即可。
到此這篇關(guān)于.NET 對象轉(zhuǎn)Json的幾種常見方式的文章就介紹到這了,更多相關(guān).NET 對象轉(zhuǎn)Json內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
ASP.NET?Core中MVC模式實(shí)現(xiàn)路由一
這篇文章介紹了ASP.NET?Core中MVC模式實(shí)現(xiàn)路由的方法,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-04-04
ASP.NET數(shù)據(jù)綁定之Repeater控件
這篇文章主要介紹了ASP.NET數(shù)據(jù)綁定中的Repeater控件,Repeater控件可以將數(shù)據(jù)庫中的信息加以綁定然后再在瀏覽器中顯示出來,感興趣的小伙伴們可以參考一下2016-01-01
.Net使用RabbitMQ實(shí)現(xiàn)短信密碼重置的操作步驟
在C#開發(fā)中,通過RabbitMQ實(shí)現(xiàn)短信服務(wù)可增強(qiáng)應(yīng)用的消息通知能力,本文介紹了使用RabbitMQ發(fā)送短信的步驟,包括安裝RabbitMQ客戶端庫、創(chuàng)建連接和通道、實(shí)現(xiàn)短信發(fā)送服務(wù)、配置RabbitMQ消費(fèi)者,并集成到用戶密碼重置流程中,通過示例代碼,可以快速理解整個(gè)實(shí)現(xiàn)過程2024-09-09
ASP.NET Core Authentication認(rèn)證實(shí)現(xiàn)方法
這篇文章主要介紹了ASP.NET Core Authentication認(rèn)證實(shí)現(xiàn)方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-08-08
ASP.NET頁面間數(shù)據(jù)傳遞的幾種方法介紹
在ASP.NET中,頁面間數(shù)據(jù)傳遞的方法有很多。下面為大家總結(jié)一下,頁面間數(shù)據(jù)傳遞的方法,來看作者的分析。2013-05-05

