如何在. NET中将C#对象转换为JSON字符串?

我有这样的类:

class MyDate{int year, month, day;}
class Lad{string firstName;string lastName;MyDate dateOfBirth;}

我想把Lad对象变成JSON字符串,如下所示:

{"firstName":"Markoff","lastName":"Chaney","dateOfBirth":{"year":"1901","month":"4","day":"30"}}

(没有格式)。我找到了此链接,但它使用了不在. NET 4中的命名空间。我也听说过JSON.NET,但他们的网站目前似乎已经关闭,我不喜欢使用外部DLL文件。

除了手动创建JSON字符串写入器之外,还有其他选项吗?

1931224 次浏览

使用DataContractJsonSerializer类:MSDN1MSDN2

我的例子:这里

JavaScriptSerializer不同,它还可以安全地从JSON字符串中反序列化对象。但就个人而言,我仍然更喜欢Json.NET

请注意

Microsoft建议您不要使用JavaScriptSerializer

查看留档页面的标题:

对于. NET Framework 4.7.2及更高版本,请使用System. Text. Json命名空间中的API进行序列化和反序列化。对于早期版本的. NET Framework,请使用Newtonsoft. Json。


原答复:

您可以使用#0类(添加对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);}}

既然我们都喜欢小笑话

…这个依赖于Newtonsoft NuGet包,它很受欢迎并且比默认的序列化程序更好。

Newtonsoft.Json.JsonConvert.SerializeObject(new {foo = "bar"})

文档:序列化和反序列化JSON

支持ServiceStack的JSON Serializer:

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字符串并填充类的字段。

它就像这样简单(它也适用于动态对象(类型对象)):

string json = newSystem.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 String:

 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);}

您可以使用NuGet的Newtonsoft.json.安装Newtonsoft.json来实现这一点。

using Newtonsoft.Json;
var jsonString = JsonConvert.SerializeObject(obj);

System.Text.Json命名空间中提供了一个新的JSON序列化程序。它包含在. NET Core 3.0共享框架中,并且在针对. NET Standard或. NET Framework或. NET Core 2. x的项目的NuGet包中。

示例代码:

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序列化程序当前不序列化字段。

文档:

在Lad模型类中,为toString()方法添加一个覆盖,该方法返回Lad对象的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);}

另一个使用System.Text.Json(. NET Core 3.0+,. NET 5)的解决方案,其中对象是自给自足的并未公开所有可能的字段:

通过测试:

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);}}}

这是另一个使用CinchooETL的解决方案-一个开源库

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}}

声明:我是这个图书馆的作者。