如何基于JTokenType简化JToken的铸造

cam*_*ous 4 c# json.net

有什么解决方案可以以更好/更短的方式重构以下开关/案例代码?

  • property.Value 是一个 JToken
  • opportunity 是CRM Dynamics实体(类似于字典)

我尝试了以下方法,但未成功(C#不可接受)

Type target = property.Value.Type.GetType();
opportunity[property.Key] = property.Value.Value<target>();
Run Code Online (Sandbox Code Playgroud)

这是我要简化的代码。(JTokenType.Object并且JTokenType.Array以其他方式处理。)

                switch (property.Value.Type)
                {
                    case JTokenType.Boolean:
                        opportunity[property.Key] = property.Value.Value<bool>();
                        break;
                    case JTokenType.Date:
                        opportunity[property.Key] = property.Value.Value<DateTime>();
                        break;
                    case JTokenType.Integer:
                        opportunity[property.Key] = property.Value.Value<int>();
                        break;
                    case JTokenType.String:
                        opportunity[property.Key] = property.Value.Value<string>();
                        break;
                    case JTokenType.Guid:
                        opportunity[property.Key] = property.Value.Value<Guid>();
                        break;
                }
Run Code Online (Sandbox Code Playgroud)

我也尝试过@diiN_的建议:

opportunity[property.Key] = property.Value.Value<dynamic>();
Run Code Online (Sandbox Code Playgroud)

但它抛出InvalidDataContractException: 视觉工作室例外

Bri*_*ers 5

您可以尝试使用以下方法代替switch语句:

if (property.Value is JValue)
{
    opportunity[property.Key] = ((JValue)property.Value).Value;
}
Run Code Online (Sandbox Code Playgroud)

  • 很棒的解决方案,遗憾的是没有找到它。对于文化,在我的特定示例(CRM Dynamics)中,我必须覆盖 Integer 类型的行为,因为默认情况下 json.net 对于某些特定字段强制转换为 Int64 而不是 Int32。 (2认同)