0

I have an object I'd like to serialize to look somewhat like this

{
  "someStaticallyNamedObject": "Something",
  "dynamicallyNamedObject": "HelloWorld"
}

The real structure of the objects before serialization is:

[DataContract]
public class SomeData
{
  [DataMember(Name="someStaticallyNamedObject")]
  public string someStaticallyNamedObject {get;set;}
  public DynamicObj someDynamicObj;
}

public class DynamicObj
{
  private string _dynamicObjName;
  public string objectValue;
}

Ideally I don't want to use the SomeData object. I want to write my custom serialization logic only for DynamicObj.

Any help will be appreciated.

Maciej Musialek
  • 56
  • 1
  • 14
  • Possible duplicate of [Serialize Dynamic Property Name for an Object using JSON.NET](https://stackoverflow.com/q/22718759/10263) – Brian Rogers Nov 06 '18 at 16:47
  • Something like this might work for you: [JsonConverter where the property is composed of fields on its parent](https://stackoverflow.com/a/39256766/3744182). In that answer some statically named properties are serialized automatically, and some dynamically named properties are serialized using the `JsonExtensionData` mechanism. – dbc Nov 06 '18 at 16:56
  • Or, you could use a custom contract resolver to hook into the `[JsonExtensionData]` functionality, as shown e.g. in [How to serialize runtime added “properties” to Json](https://stackoverflow.com/q/46888732). – dbc Nov 06 '18 at 20:38
  • I was hoping that I could get the instance of the DynamicObj inside my CreateProperty override. I didn't want my contract resolver to be state dependent but if there's no other choice then this is indeed a duplicate. – Maciej Musialek Nov 07 '18 at 10:56
  • [`CreateProperty`](https://www.newtonsoft.com/json/help/html/M_Newtonsoft_Json_Serialization_DefaultContractResolver_CreateProperty.htm) (and contract resolver methods in general) define a contract for serializing a given type, and thus never receive any specific instance of the type. – dbc Nov 07 '18 at 15:47

0 Answers0