使用简单字符串

时间:2016-11-14 16:00:35

标签: json.net converter built-in

我的数据源创建表示整数数组的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>>();

我得到了一个N​​ewtonsoft.Json.JsonSerializationException。无法从System.String转换或转换为System.Collections.Generic.List`1 [System.String]。我完全理解这一点,但我想知道Newtonsoft JSON库是否有内置的方式将逗号分隔的字符串转换为List。

我想认为有一种比尝试检查变量是否是逗号分隔列表然后将其转换为List&lt;&gt;更好的方法。手动,或者也许是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 个答案:

答案 0 :(得分:1)

我可以看到三个问题:

  1. 您应该使用JArray而不是JValue。您打算将其作为一个数组,因此您需要使用Newtonsoft中的等效类来表示数组。 (我可以说,JValue代表一种简单类型 - 例如。stringnumberDate等。)
  2. 您应该使用Parse方法而不是使用构造函数。 Parse会将字符串的内容作为数组读取,但是......
  3. ...为了做到这一点,你需要用方括号包围你得到的数据,否则JArray无法正确解析数据。没有必要摆弄CMS;在解析之前先做一个字符串连接。
  4. e.g。

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