簡體   English   中英

C#寫Json文件錯誤

[英]C# Write Json file error

我想從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更改為public。

通過添加getset方法將成員轉換為屬性

public class Person
{
    public string firstName { get; set; };
    public string lastName { get; set; };
    public int height { get; set; };
    public double weight { get; set; };

    public Person() { }
    public Person(string firstName, string lastName, int height, double weight)
    {
        this.firstName = firstName;
        this.lastName = lastName;
        this.height = height;
        this.weight = weight;
    }
}

試試這個吧。

// 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);
            File.WriteAllText(@"c:\person.json", json);
            Console.WriteLine("Done");
            Console.ReadLine();

類:

public class Person
{
        public string firstName { get; set; }
        public string lastName { get; set; }
        public int height { get; set; }
        public double weight { get; set; }

        public Person() { }
        public Person(string firstName, string lastName, int height, double weight)
        {
            this.firstName = firstName;
            this.lastName = lastName;
            this.height = height;
            this.weight = weight;
        }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM