C#写Json文件错误

时间:2015-05-14 08:29:05

标签: 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仅显示:" {}"

请帮我解决此错误。

3 个答案:

答案 0 :(得分:2)

将您的代码更改为:

public string firstName;
public string lastName;
public int height;
public double weight;

私有字段未序列化。

答案 1 :(得分:1)

在类成员声明中将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;
    }
}

答案 2 :(得分:0)

试试这个。

// 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;
        }
}