我想将数据从 Object 写入 Json 文件。
我类的人
public class Person
{
private string firstName;
private string lastName;
private int height;
private double weight;
public Person() { }
public Person(string firstName, string lastName, int height, double weight)
{
this.firstName = firstName;
this.lastName = lastName;
this.height = height;
this.weight = weight;
}
}
我的程序类
class Program
{
static void Main(string[] args)
{
// serialize JSON to a string and then write string to a file
Person ps1 = new Person("Tay", "Son", 180, 99.99);
string json = JsonConvert.SerializeObject(ps1,Formatting.Indented);
File.WriteAllText(@"c:\person.json", json);
Console.WriteLine("Done");
Console.ReadLine();
}
}
person.json 只显示:“{}”
请帮我解决这个错误。
最佳答案
将您的代码更改为:
public string firstName;
public string lastName;
public int height;
public double weight;
私有(private)字段未序列化。
关于C#写Json文件报错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30232703/