简体   繁体   中英

How Serialize single value by json.net?

I am serializing the Student class using json.net .

I would like to add to the serialized object an attribute (called cheak that is not a member of the Student class.

This is class student:

public class Student 
    {
        public int ID { get; set; }
        [JsonIgnore]
        public Faculty Faculty { get; set; }
        [JsonProperty("Faculty")]
        public string FacultyName { get { return Faculty.name; } }
        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; }
    }

json:

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

I want to add the attribute "cheak" to the serialized object:

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

If you need to be able to deserialize as well as serialize object I would Inherit Student onto a new class like this

public class StudentJson : Student 
{
    public bool cheak { get; set; }
}

You can then pass this to be serialized.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM