0

When using the XElement API and asking for a particular element (via .Element("Foo")), I get back an object which, when serialized to JSON (using ASP.NET Core), results in an object with a single field (Foo), which then contains all of the child objects of Foo.

How do I make it so that all of the children of Foo are contained in the top level of the serialized object? The .Elements() method will get me the elements but I don't want them as a collection, I want them as fields on an object.

Simon Morgan
  • 2,018
  • 5
  • 23
  • 36
  • Create your class and serialize instances of this one instead of serializing `XElements`? – mm8 Apr 06 '20 at 13:45
  • I literally just want an object that's a property of some XML returned from an API as-is, so I want to avoid creating a ton of brittle boilerplate XML POCOs if at all possible. – Simon Morgan Apr 06 '20 at 13:49
  • Create a custom serializer then. – mm8 Apr 06 '20 at 13:51
  • That would involve having to create the boilerplate POCOs I said I wanted to avoid. It doesn't look like I'm going to avoid doing that, though. :-( – Simon Morgan Apr 06 '20 at 13:53
  • Apparently not since you already have tried how an `XElement` is serialized using the default serializer. – mm8 Apr 06 '20 at 13:53

1 Answers1

0

If you are not satisfied with how an XElement is serialized by the default serializer, you basically have two options.

  1. Create your custom type and serialize instances of this one.

  2. Create a custom converter for either XElement or your custom type.

If you are using System.Text.Json, which is the default one in ASP.NET Core 3.x, you inherit from System.Text.Json.Serialization.JsonConverter<T> and override the Read and Write methods.

If you are still using Newtonsoft.Json, you inherit from Newtonsoft.Json.JsonConverter<T> and override the ReadJson and WriteJson methods.

mm8
  • 163,881
  • 10
  • 57
  • 88