2

Given the following class:

public sealed class GorpCollection : IEnumerable<Gorp> {
   private readonly IReadOnlyCollection<Gorp> _gorps;
   public GorpCollection(string name, IEnumerable<Gorp> gorps) {
      _gorps = gorps.ToList().AsReadOnly();
      GorpType1 = _gorps.Where(gorp => gorp.GorpType == 1).ToList().AsReadOnly();
      GorpType2 = _gorps.Where(gorp => gorp.GorpType == 2).ToList().AsReadOnly();
      Name = name;
   }

   public string Name { get; }
   public IReadOnlyCollection GorpType1 { get; }
   public IReadOnlyCOllection GorpType2 { get; }

   public IEnumerator<Gorp> GetEnumerator => _gorps.GetEnumerator();
   IEnumerator IEnumerable.GetEnumerator() => ((IEnumerable) _gorps).GetEnumerator();
}

I would like to serialize it as its concrete class to a JSON object, and not as an IEnumerable which comes out as an array. I am content for the properties Name, GorpType1, and GorpType2 to be serialized.

What is the easiest way to do this with the least messing about with custom converters, binders, and settings? I would have thought a simple attribute was available such as [SerializeAs(typeof(GorpCollection))]. But a fair amount of searching later, and I still don't know a simple way to get this done.

ErikE
  • 48,881
  • 23
  • 151
  • 196
  • Have you tried `[JsonObject]` (more info here: http://stackoverflow.com/a/15058402/23354, which was the first hit for "json.net ignore ieumerable" in google)? – Marc Gravell Nov 29 '16 at 09:44
  • Hi @MarcGravell, I swear to you I did a fair amount of searching and did not find that. But now I see that my question is a duplicate of that one. Thank you very much! I think the attribute is not well-named to hint what it does. Even an IEnumerable is an object. :) – ErikE Nov 29 '16 at 09:48
  • @ErikE naming is hard :) For protobuf-net, I went with `[ProtoContract(IgnoreListHandling = true)]` - which kinda explains a bit more – Marc Gravell Nov 29 '16 at 09:49
  • @Rafal What exactly are you unclear on? I don't want to deserialize, I want to serialize. As I said, I am content for the properties `Name`, `GorpType`, and `GorpType2` to be serialized. If you still need an example, here's the result I'm looking for: `{"Name":"Silly","GorpType1":["A gorp"],"GorpType2":["Another gorp"]}`. I do not want `["A gorp","Another gorp"]`. – ErikE Nov 29 '16 at 09:50
  • @ErikE a yes got it now :) – Rafal Nov 29 '16 at 09:53

0 Answers0