-
Notifications
You must be signed in to change notification settings - Fork 5.1k
Add generic modeljsonconverter #36854
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
91 changes: 91 additions & 0 deletions
91
sdk/core/Azure.Core/src/Serialization/ModelJsonConverter.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,91 @@ | ||
| // Copyright (c) Microsoft Corporation. All rights reserved. | ||
| // Licensed under the MIT License. | ||
|
|
||
| using System; | ||
| using System.Linq; | ||
| using System.Text.Json; | ||
| using System.Text.Json.Serialization; | ||
|
|
||
| namespace Azure.Core.Serialization | ||
| { | ||
| /// <summary> | ||
| /// . | ||
| /// </summary> | ||
| #pragma warning disable AZC0014 // Avoid using banned types in public API | ||
| public class ModelJsonConverter : JsonConverter<IJsonSerializable> | ||
| #pragma warning restore AZC0014 // Avoid using banned types in public API | ||
| { | ||
| /// <summary> | ||
| /// . | ||
| /// </summary> | ||
| public bool IgnoreAdditionalProperties { get; } | ||
|
|
||
| /// <summary> | ||
| /// . | ||
| /// </summary> | ||
| public ModelJsonConverter() | ||
| : this(true) { } | ||
|
|
||
| /// <summary> | ||
| /// . | ||
| /// </summary> | ||
| /// <param name="ignoreAdditionalProperties"></param> | ||
| public ModelJsonConverter(bool ignoreAdditionalProperties) | ||
| { | ||
| IgnoreAdditionalProperties = ignoreAdditionalProperties; | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// . | ||
| /// </summary> | ||
| /// <param name="typeToConvert"></param> | ||
| /// <returns></returns> | ||
| public override bool CanConvert(Type typeToConvert) | ||
| { | ||
| return (typeToConvert.GetInterfaces().Any(i => i is IJsonSerializable)); | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// . | ||
| /// </summary> | ||
| /// <param name="reader"></param> | ||
| /// <param name="typeToConvert"></param> | ||
| /// <param name="options"></param> | ||
| /// <returns></returns> | ||
| /// <exception cref="NotSupportedException"></exception> | ||
| #pragma warning disable AZC0014 // Avoid using banned types in public API | ||
| public override IJsonSerializable Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) | ||
| #pragma warning restore AZC0014 // Avoid using banned types in public API | ||
| { | ||
| SerializableOptions serializableOptions = ConvertOptions(options); | ||
| var model = Activator.CreateInstance(typeToConvert, true) as IModelInternalSerializable; | ||
| if (model is null) | ||
| throw new NotSupportedException($"{typeToConvert.Name} does not have a parameterless constructor"); | ||
|
|
||
| model.Deserialize(ref reader, serializableOptions); | ||
| return (IJsonSerializable)model; | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// . | ||
| /// </summary> | ||
| /// <param name="writer"></param> | ||
| /// <param name="value"></param> | ||
| /// <param name="options"></param> | ||
| #pragma warning disable AZC0014 // Avoid using banned types in public API | ||
| public override void Write(Utf8JsonWriter writer, IJsonSerializable value, JsonSerializerOptions options) | ||
| #pragma warning restore AZC0014 // Avoid using banned types in public API | ||
| { | ||
| SerializableOptions serializableOptions = ConvertOptions(options); | ||
| ((IModelInternalSerializable)value).Serialize(writer, serializableOptions); | ||
| } | ||
|
|
||
| private SerializableOptions ConvertOptions(JsonSerializerOptions options) | ||
| { | ||
| SerializableOptions serializableOptions = new SerializableOptions(); | ||
| serializableOptions.IgnoreAdditionalProperties = IgnoreAdditionalProperties; | ||
| serializableOptions.IgnoreReadOnlyProperties = options.IgnoreReadOnlyProperties; | ||
| return serializableOptions; | ||
| } | ||
| } | ||
| } | ||
25 changes: 25 additions & 0 deletions
25
sdk/core/Azure.Core/src/Shared/IModelInternalSerializable.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,25 @@ | ||
| // Copyright (c) Microsoft Corporation. All rights reserved. | ||
| // Licensed under the MIT License. | ||
|
|
||
| using System.Text.Json; | ||
| using Azure.Core.Serialization; | ||
|
|
||
| namespace Azure.Core | ||
| { | ||
| internal interface IModelInternalSerializable | ||
| { | ||
| /// <summary> | ||
| /// TODO | ||
| /// </summary> | ||
| /// <param name="writer"></param> | ||
| /// <param name="options"></param> | ||
| void Serialize(Utf8JsonWriter writer, SerializableOptions? options = default); | ||
|
|
||
| /// <summary> | ||
| /// TODO | ||
| /// </summary> | ||
| /// <param name="reader"></param> | ||
| /// <param name="options"></param> | ||
| void Deserialize(ref Utf8JsonReader reader, SerializableOptions? options = default); | ||
| } | ||
| } |
109 changes: 109 additions & 0 deletions
109
sdk/core/Azure.Core/tests/ModelSerializationTests/ModelJsonConverterTests.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,109 @@ | ||
| // Copyright (c) Microsoft Corporation. All rights reserved. | ||
| // Licensed under the MIT License. | ||
|
|
||
| using System; | ||
| using System.Collections.Generic; | ||
| using System.Linq; | ||
| using System.Text; | ||
| using System.Text.Json; | ||
| using System.Threading.Tasks; | ||
| using Azure.Core.Serialization; | ||
| using NUnit.Framework; | ||
|
|
||
| namespace Azure.Core.Tests.ModelSerializationTests | ||
| { | ||
| public class ModelJsonConverterTests | ||
| { | ||
| [TestCase(true, true)] | ||
| [TestCase(true, false)] | ||
| [TestCase(false, true)] | ||
| [TestCase(false, false)] | ||
| public void SerializeTest(bool ignoreReadonlyProperties, bool ignoreAdditionalProperties) | ||
| { | ||
| JsonSerializerOptions options = new JsonSerializerOptions(); | ||
| options.Converters.Add(new ModelJsonConverter(ignoreAdditionalProperties)); | ||
| options.IgnoreReadOnlyProperties = ignoreReadonlyProperties; | ||
|
|
||
| string expected = "{"; | ||
| if (!ignoreReadonlyProperties) | ||
| expected += "\"latinName\":\"Animalia\","; | ||
| expected += "\"name\":\"Doggo\",\"isHungry\":false,"; | ||
| expected += "\"weight\":1.5,"; | ||
| expected += "\"foodConsumed\":[\"kibble\",\"egg\",\"peanut butter\"]}"; | ||
| var dog = new DogListProperty | ||
| { | ||
| Name = "Doggo", | ||
| IsHungry = false, | ||
| Weight = 1.5, | ||
| FoodConsumed = { "kibble", "egg", "peanut butter" }, | ||
| }; | ||
| var actual = JsonSerializer.Serialize(dog, options); | ||
| Assert.AreEqual(expected, actual); | ||
| } | ||
|
|
||
| [TestCase(true, true)] | ||
| [TestCase(true, false)] | ||
| [TestCase(false, true)] | ||
| [TestCase(false, false)] | ||
| public void DeserializeTest(bool ignoreReadonlyProperties, bool ignoreAdditionalProperties) | ||
| { | ||
| string serviceResponse = "{\"latinName\":\"Animalia\",\"weight\":1.5,\"name\":\"Doggo\",\"isHungry\":false,\"foodConsumed\":[\"kibble\",\"egg\",\"peanut butter\"],\"numberOfLegs\":4}"; | ||
|
|
||
| JsonSerializerOptions options = new JsonSerializerOptions(); | ||
| options.Converters.Add(new ModelJsonConverter(ignoreAdditionalProperties)); | ||
| options.IgnoreReadOnlyProperties = ignoreReadonlyProperties; | ||
|
|
||
| var dog = JsonSerializer.Deserialize<DogListProperty>(serviceResponse, options); | ||
|
|
||
| Assert.AreEqual("Doggo", dog.Name); | ||
| Assert.AreEqual(false, dog.IsHungry); | ||
| Assert.AreEqual(1.5, dog.Weight); | ||
| CollectionAssert.AreEquivalent(new List<string> { "kibble", "egg", "peanut butter" }, dog.FoodConsumed); | ||
| Assert.AreEqual("Animalia", dog.LatinName); | ||
|
|
||
| var additionalProperties = typeof(Animal).GetProperty("RawData", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).GetValue(dog) as Dictionary<string, BinaryData>; | ||
| Assert.IsNotNull(additionalProperties); | ||
| Assert.AreEqual(!ignoreAdditionalProperties, additionalProperties.ContainsKey("numberOfLegs")); | ||
| if (!ignoreAdditionalProperties) | ||
| Assert.AreEqual("4", additionalProperties["numberOfLegs"].ToString()); | ||
|
|
||
| string expected = "{"; | ||
| if (!ignoreReadonlyProperties) | ||
| expected += "\"latinName\":\"Animalia\","; | ||
| expected += "\"name\":\"Doggo\",\"isHungry\":false,"; | ||
| expected += "\"weight\":1.5,"; | ||
| expected += "\"foodConsumed\":[\"kibble\",\"egg\",\"peanut butter\"]"; | ||
| if (!ignoreAdditionalProperties) | ||
| expected += ",\"numberOfLegs\":4"; | ||
| expected += "}"; | ||
|
|
||
| var actual = JsonSerializer.Serialize(dog, options); | ||
| Assert.AreEqual(expected, actual); | ||
| } | ||
|
|
||
| [Test] | ||
| public void UsesMoreConcreteConverter() | ||
| { | ||
| string serviceResponse = "{\"latinName\":\"Animalia\",\"weight\":1.5,\"name\":\"Doggo\",\"isHungry\":false,\"foodConsumed\":[\"kibble\",\"egg\",\"peanut butter\"],\"numberOfLegs\":4}"; | ||
|
|
||
| JsonSerializerOptions options = new JsonSerializerOptions(); | ||
| options.Converters.Add(new ModelJsonConverter()); | ||
| options.Converters.Add(new DogListPropertyBlankConverter()); | ||
|
|
||
| //the more concrete converter should be used so we will validate the default values are used | ||
| var dog = JsonSerializer.Deserialize<DogListProperty>(serviceResponse, options); | ||
| Assert.AreEqual("Animal", dog.Name); | ||
| Assert.AreEqual(false, dog.IsHungry); | ||
| Assert.AreEqual(1.1d, dog.Weight); | ||
| CollectionAssert.AreEquivalent(new List<string>(), dog.FoodConsumed); | ||
| Assert.AreEqual("Animalia", dog.LatinName); | ||
|
|
||
| var additionalProperties = typeof(Animal).GetProperty("RawData", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).GetValue(dog) as Dictionary<string, BinaryData>; | ||
| Assert.IsNotNull(additionalProperties); | ||
| Assert.AreEqual(0, additionalProperties.Count); | ||
|
|
||
| var actual = JsonSerializer.Serialize(dog, options); | ||
| Assert.AreEqual("", actual); | ||
| } | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
won't
Activator.CreateInstancealready throw if a suitable constructor is not available? Seems like the error should be related to the not implementingIModelInternalSerializable