Newtonsoft Json Json带有简单字符串的 SerializationException

Newtonsoft Json JsonSerializationException with simple string

我的数据源创建了 JSON,表示整数数组“1,2,3,4,5”。我对此无能为力(比如将其更改为 [1,2,3,4,5]),这是一个我们必须处理的企业 CMS。

我正在尝试阅读 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. 您应该使用 JArray 而不是 JValue。您希望这是一个数组,因此您需要在 Newtonsoft 中使用等效的 class 来表示一个数组。 (据我所知,JValue 代表一个简单的类型——例如 stringnumberDate 等)
  2. 您应该使用 Parse 方法而不是使用构造函数。 Parse 会将字符串的内容作为数组读取,但是...
  3. ...为了做到这一点,您需要用方括号括起您获得的数据,否则 JArray 无法正确解析数据。 CMS 不需要fiddle;在你解析之前做一个字符串连接。

例如

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