如何将 C# 类对象转换为 json? [复制]
Posted
技术标签:
【中文标题】如何将 C# 类对象转换为 json? [复制]【英文标题】:How to convert C# class object to json? [duplicate] 【发布时间】:2021-09-08 07:13:46 【问题描述】:我有 2 个类,用户和用户响应:
public class User
public int Id get; set;
public string FirstName get; set;
public string LastName get; set;
public decimal Balance get; set;
public class UserResponse
public User UserInfo get; set;
public string Age get; set;
public string Gender get; set;
public string Message get; set;
这是我想要收到的:
"userInfo":
"id": "1",
"firstName": "John",
"lastName": "Doe",
"balance": "1000"
,
"age": "25",
"gender": "Male",
"message": "Hello",
所以问题是如何将 UserResponse 类转换为我想要的 json?
【问题讨论】:
你需要的是序列化。有很多工具和库可供您使用并将对象序列化为 json。最佳选择是 System.Text.Json 和 Newtonsoft.Json 是的,理论上我知道我需要序列化,但是我不知道构建方法的语法。 【参考方案1】:我相信您是新手,想要一个工作样本来开始这项工作。
给你。
using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
public class Program
public static void Main()
var o = new UserResponse();
o.Age = "25";
o.Gender = "Male";
o.Message = "Hello";
o.UserInfo = new User();
o.UserInfo.Id = 1;
o.UserInfo.FirstName = "John";
o.UserInfo.LastName = "Doe";
o.UserInfo.Balance = 1000M;
var json = JsonConvert.SerializeObject(o, Formatting.Indented, new JsonSerializerSettings ContractResolver = new CamelCasePropertyNamesContractResolver() );
Console.WriteLine(json);
public class User
public int Id get; set;
public string FirstName get; set;
public string LastName get; set;
public decimal Balance get; set;
public class UserResponse
public User UserInfo get; set;
public string Age get; set;
public string Gender get; set;
public string Message get; set;
在这里试试...
Sample Code
【讨论】:
【参考方案2】:你可以使用 JavascripSerializer
using System.Web.Script.Serialization;
var json = new javascriptSerializer().Serialize(objUserResponse);
【讨论】:
我也可以使用newtonsoft json吗?还是那另一种?【参考方案3】:您可以使用 System.Text.Json 中的 JsonSerializer
using System;
using System.Text.Json;
public class Program
public static void Main()
UserResponse response = new UserResponse Age = "35", Gender = "male", Message = "Hello", UserInfo = new User Id = 1, Balance = 5.00m, FirstName = "John", LastName = "Smith" ;
Console.WriteLine(JsonSerializer.Serialize(response, new JsonSerializerOptions PropertyNamingPolicy = JsonNamingPolicy.CamelCase, WriteIndented = true));
public class User
public int Id get; set;
public string FirstName get; set;
public string LastName get; set;
public decimal Balance get; set;
public class UserResponse
public User UserInfo get; set;
public string Age get; set;
public string Gender get; set;
public string Message get; set;
;
结果:
"userInfo":
"id": 1,
"firstName": "John",
"lastName": "Smith",
"balance": 5.00
,
"age": "35",
"gender": "male",
"message": "Hello"
您可以在这里找到详细信息:https://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-customize-properties
【讨论】:
以上是关于如何将 C# 类对象转换为 json? [复制]的主要内容,如果未能解决你的问题,请参考以下文章