使用JsonConvert序列化对象时没有结果

时间:2017-03-23 11:38:55

标签: c# json visual-studio json.net

这是我的班级:

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;
        }
    }

将其对象转换为文本的代码:

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

但是在文字中我得到了这个{}

3 个答案:

答案 0 :(得分:3)

Json.NET的默认行为只处理公共字段。所以改变你的非公共领域,如下:

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

如果您无法公布字段,另一种解决方法是使用Json.Net的 JsonProperty 属性,如下所示:

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

答案 1 :(得分:2)

您将获得一个空白文本json对象,因为您的所有属性都不公开。默认情况下,它们是内部的,不会被序列化。

答案 2 :(得分:0)

JsonConvert需要公开属性和字段才能序列化它们。即string firstName;应为public string firstName;。如果您无法公开这些字段,请考虑使用自定义Converter