OldIt
OldIt

Reputation: 17

JSonNet object serialization

I used "Newtonsoft.Json" in serialization. I have class "student" and class "Faculty" in my application ,when I serialize class student ,I compulsory get Faculty object in json code.

This class Student which i want serialize to 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; }
}

class Faculty inside class student :

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

code after serialize :

{
      "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",
     }

how convert last code to serialize same that ,i want show Faculty not object i want show just name.

   {
      "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",
     }

Upvotes: 0

Views: 179

Answers (1)

mroach
mroach

Reputation: 2468

One way to handle this is to use Json.Net property attributes

Try this:

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

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

The downside with this is that you won't be able to deserialize your JSON back to .NET objects. But you'll get the output you want.

Upvotes: 1

Related Questions