2015-05-14 92 views
1

我想从Object写入数据到Json文件。C#写入Json文件错误

我Person类

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只显示: “{}”

请帮我解决这个错误。

回答

2

你的代码更改为:

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

私人领域是不会被序列化。

+0

好的,谢谢。有用 – anhtv13

1

在班级成员声明中更改为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; 
    } 
} 
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; 
     } 
}