为什么我的JavaScriptSerializer返回空的JSON对象? [英] Why is my JavaScriptSerializer returning empty json objects?

查看:128
本文介绍了为什么我的JavaScriptSerializer返回空的JSON对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有个数据点的名单,定义如下:

 公共类点{
线率;
线日期;
串号;

公共点(串速率,字符串日期,串号)
{
this.Rate =率;
this.Date =日期;
this.Number =数量;
}
}



然后我的代码中我有:



 列表<点和GT;点= populatedList; 
的JavaScriptSerializer的JavaScriptSerializer =新的JavaScriptSerializer();

字符串文本= javaScriptSerializer.Serialize(点);

System.IO.File.WriteAllText(@C:\Users\Public\WriteText.txt,文本);

当我去查看WriteText.txt,然而,我只有一堆空括号: {},{},{} ... 我也试图与只有一点这样做,然后我留下只有一对匹配括号。然后,我尝试单独序列化一个String对象,并且工作得很好。为什么的JavaScriptSerializer 没有表现如预期?


解决方案

有关类成员和结构成员,包括嵌套类和结构的访问级别,默认情况下是私有的。 - 访问修饰符 MSDN


< /块引用>

作为一个结果,序列将不会看到这些属性。为了让他们成为系列化,他们需要被标记为公开。他们还需要有一个公共的getter为了串行读取属性



 公共字符串率{搞定;组; } 
公共字符串日期{搞定;组; }
公共串号{搞定;组; }


I have a list of data points, as defined below:

public class Point {
    string Rate;
    string Date;
    string Number;

    public Point(string Rate, string Date, string Number)
    {
        this.Rate = Rate;
        this.Date = Date;
        this.Number = Number;
    }
}

Then within my code I have:

List<Point> points = populatedList;
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();

string text = javaScriptSerializer.Serialize(points);

System.IO.File.WriteAllText(@"C:\Users\Public\WriteText.txt", text);

When I go to view "WriteText.txt", however, all I have is a bunch of empty brackets: {}, {}, {} ... I have also tried doing this with only one point, and then I am left with only one matching pair of brackets. I then tried serializing a string object alone and that worked fine. Why is the JavaScriptSerializer not behaving as expected?

解决方案

The access level for class members and struct members, including nested classes and structs, is private by default. - Access ModifiersMSDN

As a result of that, the serialization will not see those properties. In order for them to be serialized, they need to be marked as public. They also need to have a public getter in order for the serializer to read the property.

public string Rate { get; set; }
public string Date { get; set; }
public string Number { get; set; }

这篇关于为什么我的JavaScriptSerializer返回空的JSON对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆