2015-05-14 82 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; 
     } 
}