Skip to content

Commit 8803295

Browse files
authored
Fix converter condition to ignore non IJsonModel (Azure#49502)
* Fix converter condition * add mixed test case
1 parent 58c2f13 commit 8803295

File tree

2 files changed

+45
-1
lines changed

2 files changed

+45
-1
lines changed

sdk/core/System.ClientModel/src/ModelReaderWriter/JsonModelConverter.cs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,8 @@ public JsonModelConverter(ModelReaderWriterOptions options, ModelReaderWriterCon
6464
/// <inheritdoc/>
6565
public override bool CanConvert(Type typeToConvert)
6666
{
67-
return !Attribute.IsDefined(typeToConvert, typeof(JsonConverterAttribute));
67+
return typeof(IJsonModel<object>).IsAssignableFrom(typeToConvert) &&
68+
!Attribute.IsDefined(typeToConvert, typeof(JsonConverterAttribute));
6869
}
6970

7071
/// <inheritdoc/>

sdk/core/System.ClientModel/tests/internal/ModelReaderWriter/JsonModelConverterTests.cs

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -155,6 +155,49 @@ public void ConvertWithBadContext()
155155
Assert.AreEqual("Either PersistableModel or the PersistableModelProxyAttribute defined needs to implement IJsonModel.", ex!.Message);
156156
}
157157

158+
[Test]
159+
public void ConverterAddedWithNoJsonModel()
160+
{
161+
var data = new Person
162+
{
163+
Name = "John Doe"
164+
};
165+
var jsonOptions = new JsonSerializerOptions { Converters = { new JsonModelConverter() } };
166+
string json = JsonSerializer.Serialize(data, jsonOptions);
167+
Assert.AreEqual("{\"Name\":\"John Doe\"}", json);
168+
}
169+
170+
private class Person
171+
{
172+
public string? Name { get; init; }
173+
}
174+
175+
[Test]
176+
public void ConverterAddedWithMixedJsonModel()
177+
{
178+
var data = new PersonMixed
179+
{
180+
Name = "John Doe",
181+
Model = new ModelX()
182+
{
183+
Name = "MyName",
184+
}
185+
};
186+
var jsonOptions = new JsonSerializerOptions { Converters = { new JsonModelConverter() } };
187+
string json = JsonSerializer.Serialize(data, jsonOptions);
188+
Assert.AreEqual("{\"Name\":\"John Doe\",\"Model\":{\"kind\":\"X\",\"name\":\"MyName\",\"fields\":[],\"keyValuePairs\":{},\"xProperty\":0}}", json);
189+
190+
//without converter we should get PascalCase and different property order
191+
string json2 = JsonSerializer.Serialize(data);
192+
Assert.AreEqual("{\"Name\":\"John Doe\",\"Model\":{\"XProperty\":0,\"Fields\":[],\"KeyValuePairs\":{},\"Kind\":\"X\",\"Name\":\"MyName\"}}", json2);
193+
}
194+
195+
private class PersonMixed
196+
{
197+
public string? Name { get; init; }
198+
public ModelX? Model { get; init; }
199+
}
200+
158201
private static Dictionary<string, BinaryData> GetRawData(object model)
159202
{
160203
Type modelType = model.GetType();

0 commit comments

Comments
 (0)