2013-04-20 52 views
0

我在序列化中使用了「Newtonsoft.Json」。 在我的應用程序中,我有班級「學生」和班級「學院」,當我序列化班級學生時,我強制以json代碼獲取Faculty對象。JSonNet對象序列化

這個班級學生,我想序列化爲json。一流的學生裏面

public class Student 
      { 
       public int ID { get; set; } 
       **public Faculty Faculty { get; set; } 
       public double AVG { get; set; } 
       public DateTime DateOfBirth { get; set; } 
       public string EducationInfo { get; set; } 
       public string FatherName { get; set; } 
       public string FirstName { get; set; } 
       public string LastName { get; set; } 
       public string MotherName { get; set; } 
       public string Password { get; set; } 
       public string PersonalInfo { get; set; } 
} 

一流的師資:連載後

public class Faculty 
     { 
      public int id { get; set; } 
      public string name { get; set; } 
      public Student[] student { get; set; } 
     } 

代碼:

{ 
     "ID": 24, 
     "Faculty": { 
     "id": 0, 
     "name": "engen", 
     "student": null 
       }, 
     "AVG": 3.0, 
     "DateOfBirth": "1990-02-02T00:00:00", 
     "EducationInfo": "GOOD", 
     "FatherName": "EEWF", 
     "FirstName": "FFEWR", 
     "LastName": "ERF", 
     "MotherName": "ERF", 
     "Password": "e2DW", 
     "PersonalInfo": "ERF", 
    } 

如何最後代碼轉換爲序列相同的是,我想展現學院不是我想要顯示名字的對象。處理這種

{ 
     "ID": 24, 
     "Faculty": "engen", 
     "AVG": 3.0, 
     "DateOfBirth": "1990-02-02T00:00:00", 
     "EducationInfo": "GOOD", 
     "FatherName": "EEWF", 
     "FirstName": "FFEWR", 
     "LastName": "ERF", 
     "MotherName": "ERF", 
     "Password": "e2DW", 
     "PersonalInfo": "ERF", 
    } 

回答

1

一種方法是使用Json.Net財產屬性

試試這個:

[JsonIgnore] 
public Faculty Faculty { get; set; } 

[JsonProperty("Faculty")] 
public string FacultyName { get { return Faculty.Name; } } 

這樣做的缺點是,你將無法反序列化JSON返回到.NET對象。但是你會得到你想要的輸出。

+0

如果我把「JsonIgnore」代碼中。我可以在其他josn序列化中使用faculty對象。 – OldIt 2013-04-20 15:37:34

+0

'JsonIgnore'屬性只會影響'Student'類中'Faculty' *屬性*的序列化方式。如果你自己序列化一個'Faculty'對象,那麼這個屬性根本不會影響它。 – mroach 2013-04-20 15:44:46