Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does c# JavaScriptSerializer.Serialize return empty square brackets

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

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

Many thanks.

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.

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.

like image 518
user2282496 Avatar asked Apr 15 '13 12:04

user2282496


1 Answers

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

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.

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; }
    ...
}
like image 76
James Avatar answered Sep 28 '22 05:09

James