我有这样的类:
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字符串写入器,还有其他选项吗?
序列化器
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
}
}
请注意
微软建议不要使用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);
}
}
如果它们不是很大,那就导出为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);
}
使用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);
反序列化到Object:
var obj = Newtonsoft.Json.JsonConvert.DeserializeObject<Lad>(jsonString );