简体   繁体   中英

Getting no result when Serializing a Object using JsonConvert

This is my class :

class teacher_details_uploadable
    {
         string firstName;
         string lastName;
         string contactNumber;
         string emailaddress;
        List<string> classes_names = new List<string>();
        List<all_class_details> all_the_classes_under_teacher = new List<all_class_details>();
        public teacher_details_uploadable()
        {
            firstName = Teacher.FirstName;
            lastName = Teacher.Lastname;
            contactNumber = Teacher.Contactnumber;
            emailaddress = Teacher.Emailaddress;
            classes_names = Teacher.Classes_Names;
            all_the_classes_under_teacher = Teacher.All_the_classes_under_teacher;
        }
    }

Code for converting its object into text:

teacher_details_uploadable teacher = new teacher_details_uploadable();
            var text=JsonConvert.SerializeObject(teacher);

But in text i get this {}

Json.NET's default behavior only processes fields that are public. So change your non-public fields like so:

 public string firstName;
 public string lastName;
 public string contactNumber;
 public string emailaddress;
 ...

Another work around, if you're unable publicize the fields, is to use the JsonProperty attribute of Json.Net as shown below:

class teacher_details_uploadable
    {    [JsonProperty]
         string firstName;
         [JsonProperty]
         string lastName;
         [JsonProperty]
         string contactNumber;
         [JsonProperty]
         string emailaddress;
         ...

You're getting a blank text json object because none of your properties are public. By default they are internal, and will not be serialized.

Properties and fields need to be public for JsonConvert to be able to serialize them. Ie string firstName; should be public string firstName; . If you cannot make these fields public consider using a custom Converter .

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