随着.NET Core的发展,BinaryFormatter已经被标记为过时。因此,我们可以使用JsonConvert.DeserializeObject方法来替代。
以下是一个示例代码,展示了如何从JSON文件中反序列化对象图并返回相应的类型:
using Newtonsoft.Json;
//定义一个待反序列化的类
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public Address Address { get; set; }
}
public class Address
{
public string City { get; set; }
public string State { get; set; }
}
//在Json文件中序列化对象
string json = @"{
'Name': 'John Doe',
'Age': 30,
'Address': {
'City': 'New York',
'State': 'NY'
}
}";
//反序列化并返回对象实例
Person person = JsonConvert.DeserializeObject(json);
通过调用JsonConvert.DeserializeObject