/// <summary> /// Serialize the object with the root. If no valid root can be determined, the object will be serialized as is. /// </summary> /// <param name="entity">The object to serialize</param> /// <param name="outputPayloadFormatOptions">Options for serialization</param> /// <returns>The entity as a serialized JSON string</returns> public static string SerializeWithRoot(object entity, OutputPayloadFormatOptions outputPayloadFormatOptions) { // get the type name if (entity == null) return string.Empty; var typeName = GetTypeNameForSerialization(entity, outputPayloadFormatOptions); var responseObject = string.IsNullOrEmpty(typeName) ? entity : new Dictionary<string, object> { [typeName] = entity }; return SerializeJson(responseObject); }
public void SerializeWithRoot_SerializesPluralObjectsByType() { // arrange var obj = new List<TestClass>(); var options = new OutputPayloadFormatOptions(); options.UseClassNames(); var expected = SerializationService.SerializeJson(new { TestClasses = obj }); // act var result = SerializationService.SerializeWithRoot(obj, options); // assert Assert.Equal(expected, result); }
public void SerializeWithRoot_ReturnsSerializedObjectAsIsIfNoValidTypeNameCanBeFound() { // arrange const string content = "this is a string"; var expected = SerializationService.SerializeJson(content); var obj = new TestClass(); var options = new OutputPayloadFormatOptions(); options.UseAttributeDefinition(); // act var result = SerializationService.SerializeWithRoot(content, options); // assert Assert.Equal(expected, result); }
private static string GetTypeNameForSerialization(object entity, OutputPayloadFormatOptions outputPayloadFormatOptions) { switch (outputPayloadFormatOptions.GetFormatterStrategy()) { case PayloadFormatOptions.FormatterStrategies.ClassName: // get the typeName from the class name return FormatTypeNameForDirectDeserialization(entity); case PayloadFormatOptions.FormatterStrategies.Dictionary: // get the typeName from the SerializationDefinitions return outputPayloadFormatOptions.SerializationDefinitions.FirstOrDefault(x => x.Key == entity.GetType()).Value; case PayloadFormatOptions.FormatterStrategies.Attribute: // get the typeName from the attributes on the class return FormatTypeNameForAttributeDeserialization(entity); default: throw new ArgumentOutOfRangeException(); } }