2016-11-14 61 views
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 

回答

1

你必须从我所看到的三个问题:

  1. 您应该使用JArrayJValue。你打算这是一组东西,所以你需要使用Newtonsoft中的等价类来表示一个数组。 (A JValue,尽我可以告诉,表示简单的类型 - e.g stringnumberDate等)
  2. 您应该使用Parse方法与使用构造。 Parse将读取字符串的内容作为一个数组,但是...
  3. ...为了做到这一点,你将需要围绕你用方括号或JArray得到的数据不能正确解析数据。没有必要摆弄CMS;在解析之前只需要一个字符串concat。

例如

JArray theValue = JArray.Parse("[" + "1,2,3" + "]"); 
+0

这确实解决了这个问题。我相信轻微的字符串操作是可以接受的解决方案,特别是当我知道我期望的类型是逗号分隔的整数列表时,我想要的类型是列表。另外,仅供参考,JValue是Newtonsoft在尝试反序列化“1,2,3,4,5”时提供给我的。我只是编写代码来向你展示我的问题。感谢您的快速解决方法! – CarComp