0
我的数据源创建表示整数数组的JSON为“1,2,3,4,5”。我无法对此做任何事情(如将其更改为[1,2,3,4,5]),这是我们必须处理的企业CMS。简单字符串的Newtonsoft Json JsonSerializationException
我想在newtonsoft ToObject方法如何处理下面的代码阅读起来:
JValue theValue = new JValue("1,2,3")
List<int> x = theValue.ToObject<List<int>>();
我得到一个Newtonsoft.Json.JsonSerializationException。无法强制转换或从System.String转换为System.Collections.Generic.List`1 [System.String]。我完全理解这一点,但我想知道Newtonsoft JSON库是否有内置的方式将逗号分隔的字符串转换为List。
我想有一个比试图检查变量是否是逗号分隔列表更好的方法,然后将其手动转换为列表<>或者可能是JArray,但我错了之前!
编辑
我想分享我的解决方案:
dynamic theValue = new JValue("1,2,3,4"); /// This is just passed in, i'm not doing this on purpose. Its to demo.
if (info.PropertyType == typeof (List<int>))
{
if (info.CanWrite)
{
if (theValue.GetType() == typeof (JValue) && theValue.Value is string)
{
theValue = JArray.Parse("[" + theValue.Value + "]");
}
info.SetValue(this, theValue.ToObject<List<int>>());
}
} else {
// do other things
这确实解决了这个问题。我相信轻微的字符串操作是可以接受的解决方案,特别是当我知道我期望的类型是逗号分隔的整数列表时,我想要的类型是列表。另外,仅供参考,JValue是Newtonsoft在尝试反序列化“1,2,3,4,5”时提供给我的。我只是编写代码来向你展示我的问题。感谢您的快速解决方法! –
CarComp