Why C # JavaScriptSerializer.Serialize returns 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); 

PS class dg is as follows:

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

Thank you very much.

THANKS - RESPONSIBLE SUCCESSFULLY - IEnumerable became the source of my problems. To solve this problem, dg no longer extends IEnumerable, and all foreach loops (dg ...) were converted back to for loops (int i = 0 ...).

THANKS VERY VERY MUCH! James understood why it was empty, Parv understood why it had square brackets. Mark as the answer, but also mark only one.

+6
source share
2 answers

Looking at the source of the problem will be a combination of several things.

Since @Parv already indicated why you get [] , this is because your class implements IEnumerable , so the serializer tries to iterate over the object and then serialize each element independently. Your current project will not work, as it is not intended to serialize public properties for types that implement IEnumerable .

Another problem, as I mentioned in the comment, is that your class does not have any public properties, what you currently have public variables. In order for the serializer to work, you need to set the / getters property.

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

The problem may be that since the dg class inherits IEnumerable , the JavaScriptSerializer treats it as an Array and therefore square brackets.

Try to do

 var result = serializer.Serialize( new dg(1999, "hithere").Select(d => new{ id = d.id, title = d.title })); 
+3
source

All Articles