Skip to content

Commit

Permalink
Fix casting issue
Browse files Browse the repository at this point in the history
  • Loading branch information
jcheng committed Apr 19, 2022
1 parent 269e572 commit 7b06dce
Showing 1 changed file with 1 addition and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,7 @@ public class TrustedJsonFactory : JsonFactory
public override Dictionary<string, object> Create(string json)
{
Dictionary<string, object> result =
(Dictionary<string, object>)JsonConvert.DeserializeObject(
json);
JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
return result;
}

Expand Down

1 comment on commit 7b06dce

@johnxjcheng
Copy link

@johnxjcheng johnxjcheng commented on 7b06dce Apr 19, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The original code used runtime cast on the result of DeserializeObject, which generally does not work in many cases. Below are two examples that show casting can fail. Where the first one is using the JSON from a real test of ours. The fix of this is to use another version: DeserializeObject<T>, which is also demonstrated in the test with success.

`
[Fact]
public void JsonConvertTest()
{
var json =
"{'schemas':['urn:ietf:params:scim:schemas:core:2.0:User','urn:ietf:params:scim:schemas:extension:enterprise:2.0:User'],'externalId':'682448d7-684b-43ea-a58d-f4862cf7ee0f','id':null,'userName':'[email protected]','active':true,'displayName':'cli test simple with email','emails':[{'primary':true,'type':'work','value':'[email protected]'}],'meta':{'resourceType':'User'},'urn:ietf:params:scim:schemas:extension:enterprise:2.0:User':{}}";

object dictionary;

// cannot cast 'Newtonsoft.Json.Linq.JObject' to type 'System.Collections.Generic.Dictionary`
Assert.Throws<InvalidCastException>(() => dictionary = (Dictionary<string, object>) JsonConvert.DeserializeObject(json));

dictionary = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
Assert.NotNull(dictionary);

}

[Fact]
public void JsonConvertTest2()
{
var json = "[1, 2, 3, 5]";
object list;

// cannot cast JArray to List
Assert.Throws<InvalidCastException>(() => list = (List<int>)JsonConvert.DeserializeObject(json));

list = JsonConvert.DeserializeObject<List<int>>(json);
Assert.NotNull(list);

}

`

Please sign in to comment.