Skip to content

Commit

Permalink
Provide type as hint to JsonSerializer
Browse files Browse the repository at this point in the history
Pass the `Type` value to `JsonSerializer` to give a hint as to how to serialize the value.
See #2593 (comment).
  • Loading branch information
martincostello committed Apr 16, 2024
1 parent 4a8806b commit 2159bba
Showing 1 changed file with 9 additions and 9 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public DataContract GetDataContractForType(Type type)
{
return DataContract.ForDynamic(
underlyingType: type,
jsonConverter: JsonConverterFunc);
jsonConverter: (value) => JsonConverterFunc(value, type));
}

if (PrimitiveTypesAndFormats.ContainsKey(type))
Expand All @@ -34,7 +34,7 @@ public DataContract GetDataContractForType(Type type)
underlyingType: type,
dataType: primitiveTypeAndFormat.Item1,
dataFormat: primitiveTypeAndFormat.Item2,
jsonConverter: JsonConverterFunc);
jsonConverter: (value) => JsonConverterFunc(value, type));
}

if (type.IsEnum)
Expand All @@ -43,7 +43,7 @@ public DataContract GetDataContractForType(Type type)

//Test to determine if the serializer will treat as string
var serializeAsString = (enumValues.Length > 0)
&& JsonConverterFunc(enumValues.GetValue(0)).StartsWith("\"");
&& JsonConverterFunc(enumValues.GetValue(0), type).StartsWith("\"");

var primitiveTypeAndFormat = serializeAsString
? PrimitiveTypesAndFormats[typeof(string)]
Expand All @@ -53,7 +53,7 @@ public DataContract GetDataContractForType(Type type)
underlyingType: type,
dataType: primitiveTypeAndFormat.Item1,
dataFormat: primitiveTypeAndFormat.Item2,
jsonConverter: JsonConverterFunc);
jsonConverter: (value) => JsonConverterFunc(value, type));
}

if (IsSupportedDictionary(type, out Type keyType, out Type valueType))
Expand All @@ -62,27 +62,27 @@ public DataContract GetDataContractForType(Type type)
underlyingType: type,
valueType: valueType,
keys: null, // STJ doesn't currently support dictionaries with enum key types
jsonConverter: JsonConverterFunc);
jsonConverter: (value) => JsonConverterFunc(value, type));
}

if (IsSupportedCollection(type, out Type itemType))
{
return DataContract.ForArray(
underlyingType: type,
itemType: itemType,
jsonConverter: JsonConverterFunc);
jsonConverter: (value) => JsonConverterFunc(value, type));
}

return DataContract.ForObject(
underlyingType: type,
properties: GetDataPropertiesFor(type, out Type extensionDataType),
extensionDataType: extensionDataType,
jsonConverter: JsonConverterFunc);
jsonConverter: (value) => JsonConverterFunc(value, type));
}

private string JsonConverterFunc(object value)
private string JsonConverterFunc(object value, Type type)
{
return JsonSerializer.Serialize(value, _serializerOptions);
return JsonSerializer.Serialize(value, type, _serializerOptions);
}

public bool IsSupportedDictionary(Type type, out Type keyType, out Type valueType)
Expand Down

0 comments on commit 2159bba

Please sign in to comment.