DataMember被连接成逗号分隔的字符串

时间:2015-01-23 18:19:15

标签: c# datacontract

[DataContract]
[KnownType(typeof(List<string>))]
[KnownType(typeof(string))]
public class User
{
    public object websites { get; set; }
}

网站可以是字符串数组或单个字符串。如果它确实以字符串数组的形式出现......它会自动连接成逗号分隔的字符串。我该如何防止这种情况?我需要它作为列表

当我尝试使用字符串[]时,它似乎失败了:

阵列:

{
    websites: [ "http://www.google.com", "http://www.whatever.com" ]
}    

单一字符串

{
    websites: "http://www.google.com"    
}

1 个答案:

答案 0 :(得分:1)

我不确定您是否需要在User上拥有这些属性。如果没有,这段代码可以正常工作:

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Diagnostics;

class Program
{
    static void Main(string[] args)
    {
        var jsonOne = "{ websites: \"http://www.google.com\" }";
        var jsonMany = "{ websites: [ \"http://www.google.com\", \"http://www.whatever.com\" ] }";

        var userOne = JsonConvert.DeserializeObject<User>(jsonOne);
        var userMany = JsonConvert.DeserializeObject<User>(jsonMany);

        Debug.WriteLine(":: One ::");
        Print(userOne);

        Debug.WriteLine(":: Many ::");
        Print(userMany);
    }

    static void Print(User user)
    {
        if(user.websites is string)
        {
            Debug.WriteLine("This user has a single website: {0}", user.websites);
        }

        if (user.websites is JArray)
        {
            Debug.WriteLine("This user has following websites:");
            foreach (var website in (JArray)user.websites)
                Debug.WriteLine(website);
        }
    }
}

public class User
{
    public object websites { get; set; }
}

输出:

:: One ::
This user has a single website: http://www.google.com
:: Many ::
This user has following websites:
http://www.google.com
http://www.whatever.com