gpt4 book ai didi

C#写Json文件报错

转载 作者:太空宇宙 更新时间:2023-11-03 23:37:06 25 4
gpt4 key购买 nike

我想将数据从 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com