C#写Json文件报错

标签 c# json

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

相关文章:

c# - 匿名类型,什么时候有用?

c# - 如何获取 Enumerable.SequenceEqual 的 MethodInfo

IE9中的Javascript Json问题

javascript - Backbone.js Visual Studio 设置

c# - 理解这段代码 _num = (_num & ~(1L << 63));

php - 从本地主机 :8888 in objective c using json 获取数据时出现问题

php - Laravel 不会遵守状态码

json - 使用 Webhook 发送到 Microsoft Teams 的 Azure Monitor 警报 - 没有向 Teams 发送消息

c# - 是否可以为 asp.net web 表单应用程序编写 action-filter 属性?

android - 我发布了一些值并在改造中以数组形式获得响应,但出现错误