提问人:Hui 提问时间:6/1/2011 最后编辑:John SmithHui 更新时间:10/20/2023 访问量:2091095
如何在 .NET 中将 C# 对象转换为 JSON 字符串?
How do I turn a C# object into a JSON string in .NET?
问:
我有这样的课程:
class MyDate
{
int year, month, day;
}
class Lad
{
string firstName;
string lastName;
MyDate dateOfBirth;
}
我想将一个对象转换为JSON字符串,如下所示:Lad
{
"firstName":"Markoff",
"lastName":"Chaney",
"dateOfBirth":
{
"year":"1901",
"month":"4",
"day":"30"
}
}
(不带格式)。我找到了这个链接,但它使用了 .NET 4 中没有的命名空间。我也听说过 JSON.NET,但他们的网站目前似乎已经关闭,而且我不热衷于使用外部DLL文件。
除了手动创建 JSON 字符串编写器之外,还有其他选择吗?
答:
使用类:MSDN1、MSDN2。 DataContractJsonSerializer
我的例子:这里。
与 .但就我个人而言,我仍然更喜欢 Json.NET。JavaScriptSerializer
评论
注意事项
Microsoft 建议您不要使用 JavaScriptSerializer
请参阅文档页面的标题:
对于 .NET Framework 4.7.2 及更高版本,请使用 System.Text.Json 命名空间中的 API 进行序列化和反序列化。对于早期版本的 .NET Framework,请使用 Newtonsoft.Json。
原答案:
您可以使用 JavaScriptSerializer
类(添加对 :System.Web.Extensions
using System.Web.Script.Serialization;
var json = new JavaScriptSerializer().Serialize(obj);
一个完整的例子:
using System;
using System.Web.Script.Serialization;
public class MyDate
{
public int year;
public int month;
public int day;
}
public class Lad
{
public string firstName;
public string lastName;
public MyDate dateOfBirth;
}
class Program
{
static void Main()
{
var obj = new Lad
{
firstName = "Markoff",
lastName = "Chaney",
dateOfBirth = new MyDate
{
year = 1901,
month = 4,
day = 30
}
};
var json = new JavaScriptSerializer().Serialize(obj);
Console.WriteLine(json);
}
}
评论
System.Web.Extensions
ASP.NET AJAX 1.0
ASP.NET 3.5
因为我们都喜欢单行本
...这个依赖于 Newtonsoft NuGet 包,该包很受欢迎,并且比默认的序列化程序更好。
Newtonsoft.Json.JsonConvert.SerializeObject(new {foo = "bar"})
文档:序列化和反序列化 JSON
评论
我会投票给ServiceStack的JSON序列化器:
using ServiceStack;
string jsonString = new { FirstName = "James" }.ToJson();
它也是可用于 .NET 的最快 JSON 序列化程序:http://www.servicestack.net/benchmarks/
评论
呜呜!使用 JSON 框架确实更好:)
以下是我使用 Json.NET (http://james.newtonking.com/json) 的示例:
using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;
using System.IO;
namespace com.blogspot.jeanjmichel.jsontest.model
{
public class Contact
{
private Int64 id;
private String name;
List<Address> addresses;
public Int64 Id
{
set { this.id = value; }
get { return this.id; }
}
public String Name
{
set { this.name = value; }
get { return this.name; }
}
public List<Address> Addresses
{
set { this.addresses = value; }
get { return this.addresses; }
}
public String ToJSONRepresentation()
{
StringBuilder sb = new StringBuilder();
JsonWriter jw = new JsonTextWriter(new StringWriter(sb));
jw.Formatting = Formatting.Indented;
jw.WriteStartObject();
jw.WritePropertyName("id");
jw.WriteValue(this.Id);
jw.WritePropertyName("name");
jw.WriteValue(this.Name);
jw.WritePropertyName("addresses");
jw.WriteStartArray();
int i;
i = 0;
for (i = 0; i < addresses.Count; i++)
{
jw.WriteStartObject();
jw.WritePropertyName("id");
jw.WriteValue(addresses[i].Id);
jw.WritePropertyName("streetAddress");
jw.WriteValue(addresses[i].StreetAddress);
jw.WritePropertyName("complement");
jw.WriteValue(addresses[i].Complement);
jw.WritePropertyName("city");
jw.WriteValue(addresses[i].City);
jw.WritePropertyName("province");
jw.WriteValue(addresses[i].Province);
jw.WritePropertyName("country");
jw.WriteValue(addresses[i].Country);
jw.WritePropertyName("postalCode");
jw.WriteValue(addresses[i].PostalCode);
jw.WriteEndObject();
}
jw.WriteEndArray();
jw.WriteEndObject();
return sb.ToString();
}
public Contact()
{
}
public Contact(Int64 id, String personName, List<Address> addresses)
{
this.id = id;
this.name = personName;
this.addresses = addresses;
}
public Contact(String JSONRepresentation)
{
//To do
}
}
}
测试:
using System;
using System.Collections.Generic;
using com.blogspot.jeanjmichel.jsontest.model;
namespace com.blogspot.jeanjmichel.jsontest.main
{
public class Program
{
static void Main(string[] args)
{
List<Address> addresses = new List<Address>();
addresses.Add(new Address(1, "Rua Dr. Fernandes Coelho, 85", "15º andar", "São Paulo", "São Paulo", "Brazil", "05423040"));
addresses.Add(new Address(2, "Avenida Senador Teotônio Vilela, 241", null, "São Paulo", "São Paulo", "Brazil", null));
Contact contact = new Contact(1, "Ayrton Senna", addresses);
Console.WriteLine(contact.ToJSONRepresentation());
Console.ReadKey();
}
}
}
结果:
{
"id": 1,
"name": "Ayrton Senna",
"addresses": [
{
"id": 1,
"streetAddress": "Rua Dr. Fernandes Coelho, 85",
"complement": "15º andar",
"city": "São Paulo",
"province": "São Paulo",
"country": "Brazil",
"postalCode": "05423040"
},
{
"id": 2,
"streetAddress": "Avenida Senador Teotônio Vilela, 241",
"complement": null,
"city": "São Paulo",
"province": "São Paulo",
"country": "Brazil",
"postalCode": null
}
]
}
现在,我将实现构造函数方法,该方法将接收 JSON 字符串并填充类的字段。
评论
Contact
com.blogspot.jeanjmichel.jsontest.main
“啊,一个Java程序员陷入了黑暗的一面。欢迎。我们有cookies。
就这么简单(它也适用于动态对象(类型对象)):
string json = new
System.Web.Script.Serialization.JavaScriptSerializer().Serialize(MYOBJECT);
评论
序列化程序
public static void WriteToJsonFile<T>(string filePath, T objectToWrite, bool append = false) where T : new()
{
var contentsToWriteToFile = JsonConvert.SerializeObject(objectToWrite, new JsonSerializerSettings
{
Formatting = Formatting.Indented,
});
using (var writer = new StreamWriter(filePath, append))
{
writer.Write(contentsToWriteToFile);
}
}
对象
namespace MyConfig
{
public class AppConfigurationSettings
{
public AppConfigurationSettings()
{
/* initialize the object if you want to output a new document
* for use as a template or default settings possibly when
* an app is started.
*/
if (AppSettings == null) { AppSettings=new AppSettings();}
}
public AppSettings AppSettings { get; set; }
}
public class AppSettings
{
public bool DebugMode { get; set; } = false;
}
}
实现
var jsonObject = new AppConfigurationSettings();
WriteToJsonFile<AppConfigurationSettings>(file.FullName, jsonObject);
输出
{
"AppSettings": {
"DebugMode": false
}
}
如果你在 ASP.NET MVC Web 控制器中,它就像这样简单:
string ladAsJson = Json(Lad);
不敢相信没有人提到过这一点。
评论
使用 Json.Net 库,可以从 Nuget 数据包管理器下载它。
序列化为 json 字符串:
var obj = new Lad
{
firstName = "Markoff",
lastName = "Chaney",
dateOfBirth = new MyDate
{
year = 1901,
month = 4,
day = 30
}
};
var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(obj);
反序列化为对象:
var obj = Newtonsoft.Json.JsonConvert.DeserializeObject<Lad>(jsonString );
如果它们不是很大,那么您的情况可能是将其导出为 JSON。
此外,这使得它在所有平台之间具有可移植性。
using Newtonsoft.Json;
[TestMethod]
public void ExportJson()
{
double[,] b = new double[,]
{
{ 110, 120, 130, 140, 150 },
{1110, 1120, 1130, 1140, 1150},
{1000, 1, 5, 9, 1000},
{1110, 2, 6, 10, 1110},
{1220, 3, 7, 11, 1220},
{1330, 4, 8, 12, 1330}
};
string jsonStr = JsonConvert.SerializeObject(b);
Console.WriteLine(jsonStr);
string path = "X:\\Programming\\workspaceEclipse\\PyTutorials\\src\\tensorflow_tutorials\\export.txt";
File.WriteAllText(path, jsonStr);
}
可以使用 Newtonsoft.json 实现此目的。从 NuGet 安装 Newtonsoft.json。然后:
using Newtonsoft.Json;
var jsonString = JsonConvert.SerializeObject(obj);
命名空间中提供了新的 JSON 序列化程序。它包含在 .NET Core 3.0 共享框架中,并且位于面向 .NET Standard、.NET Framework 或 .NET Core 2.x 的项目的 NuGet 包中。System.Text.Json
示例代码:
using System;
using System.Text.Json;
public class MyDate
{
public int year { get; set; }
public int month { get; set; }
public int day { get; set; }
}
public class Lad
{
public string FirstName { get; set; }
public string LastName { get; set; }
public MyDate DateOfBirth { get; set; }
}
class Program
{
static void Main()
{
var lad = new Lad
{
FirstName = "Markoff",
LastName = "Chaney",
DateOfBirth = new MyDate
{
year = 1901,
month = 4,
day = 30
}
};
var json = JsonSerializer.Serialize(lad);
Console.WriteLine(json);
}
}
在此示例中,要序列化的类具有属性而不是字段;序列化程序当前不序列化字段。System.Text.Json
文档:
评论
JsonSerializer.Serialize(lad)
options
ToString()
JsonSerializer.Serialize(lad)
public override string ToString() => JsonSerializer.Serialize(this, new JsonSerializerOptions { WriteIndented = true });
在 Lad 模型类中,向 ToString() 方法添加一个重写,该方法返回 Lad 对象的 JSON 字符串版本。
注意:您需要导入 System.Text.Json;
using System.Text.Json;
class MyDate
{
int year, month, day;
}
class Lad
{
public string firstName { get; set; };
public string lastName { get; set; };
public MyDate dateOfBirth { get; set; };
public override string ToString() => JsonSerializer.Serialize<Lad>(this);
}
评论
JsonSerializer.Serialize<Lad>(this)
可以简化为JsonSerializer.Serialize(this)
JsonSerializer.Serialize(lad)
options
ToString()
public override string ToString() => JsonSerializer.Serialize(this, new JsonSerializerOptions { WriteIndented = true });
2023 年 10 月更新:
使用内置 (.NET Core 3.0+) 的另一种解决方案,其中对象是自给自足的,不会公开所有可能的字段:System.Text.Json
通过测试(使用 NUnit):
using NUnit.Framework;
namespace Intech.UnitTests
{
public class UserTests
{
[Test]
public void ConvertsItselfToJson()
{
var userName = "John";
var user = new User(userName);
var actual = user.ToJson();
Assert.AreEqual($"{{\"Name\":\"{userName}\"}}", actual);
}
}
}
实现:
using System.Text.Json;
using System.Collections.Generic;
namespace Intech
{
public class User
{
private readonly string name;
public User(string name)
{
this.name = name;
}
public string ToJson()
{
var params = new Dictionary<string, string>{{"Name", name}};
return JsonSerializer.Serialize(params);
}
}
}
评论
这是使用 Cinchoo ETL 的另一种解决方案 - 一个开源库
public class MyDate
{
public int year { get; set; }
public int month { get; set; }
public int day { get; set; }
}
public class Lad
{
public string firstName { get; set; }
public string lastName { get; set; }
public MyDate dateOfBirth { get; set; }
}
static void ToJsonString()
{
var obj = new Lad
{
firstName = "Tom",
lastName = "Smith",
dateOfBirth = new MyDate
{
year = 1901,
month = 4,
day = 30
}
};
var json = ChoJSONWriter.Serialize<Lad>(obj);
Console.WriteLine(json);
}
输出:
{
"firstName": "Tom",
"lastName": "Smith",
"dateOfBirth": {
"year": 1901,
"month": 4,
"day": 30
}
}
免责声明:我是这个库的作者。
上一个:在处理大字符串时,有没有办法在 C# 中手动释放内存?
下一个:清空一长串值得吗?
评论