为什么C#JavaScriptSerializer.Serialize返回空方括号 [英] why does c# JavaScriptSerializer.Serialize return empty square brackets

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

问题描述

为什么下面的代码返回[]时,它应该返回{ID:1999年,称号:hithere}

Why does the following code return "[ ]" when it should return "{"id":1999, "title":"hithere"}

    JavaScriptSerializer serializer = new JavaScriptSerializer();
    StringBuilder sbJsonResults = new StringBuilder();
    var result = serializer.Serialize(new dg(1999, "hithere"));

    context.Response.Clear();
    context.Response.ContentType = "application/json; charset=utf-8";
    context.Response.Cache.SetExpires(DateTime.MinValue);
    context.Response.Write(result);

PS的DG类看起来是这样的:

P.S. the dg class looks like this:

    public class dg : ScheduleObserver, ILibrary, IEnumerable {
        public int id;
        public string title;
        private List<d> dList;
        ...many getters and setters and some logic functions...
    }

    public abstract class ScheduleObserver{
        public abstract void update();
    }

    public interface ILibrary {
        List<PD> getPDs();
        void setPDs(List<PD> newPDs);
        int getCurrentIndex();
        void addPD(PD pD);
        PD getPD(int index);
    }

非常感谢

谢谢 - 成功回答了 - 这是IEnumerable的,这是我的困境的源头上解决它,DG不再扩展IEnumerable和所有的foreach(DG ...)循环已经被转换回成(INT I = 0 ...)循环。

THANKS - ANSWERED SUCCESSFULLY - it was the IEnumerable that was the source of my woes. To solve it, dg no longer extends IEnumerable and all foreach (dg...) loops have been converted back into for(int i = 0...) loops.

感谢非常非常的多!詹姆斯拿到为什么它的空,Parv了为什么有括号。既能标记为答案,但只能标注有一个

THANKS VERY, VERY MUCH! JAMES got why its empty, Parv got why had square brackets. Would mark both as answer but can only mark one.

推荐答案

综观的来源问题似乎是两件事情的组合。

Looking at the source the problem would appear to be a combination of a couple of things.

由于@Parv已经指出了原因你得到的 [] 是因为你的类实现的IEnumerable 所以串行尝试的迭代对象,然后独立地序列的每个项目。您当前的设计是行不通的,因为它的目的不是要序列化公共属性为实现的IEnumerable 类型。

As @Parv has already pointed out the reason you get the [] is because your class implements IEnumerable so the serializer attempts to iterate the object and then serialize each item independently. Your current design is not going to work as it isn't designed to serialize public properties for types that implement IEnumerable.

另一个问题,就像我的评论中提到,是你的类没有出现任何公共属性,你此刻什么是公共的变量的。为了使序列化工作,你需要的setter / getter方法即

The other issue, like I mentioned in a comment, is the your class doesn't appear to have any public properties, what you have at the moment are public variables. In order for the serializer to work you need property setter/getters i.e.

public class dg
{
    public int id { get; set; }
    public string title { get; set; }
    ...
}

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

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