代码之家  ›  专栏  ›  技术社区  ›  Jimmyt1988

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

  •  0
  • Jimmyt1988  · 技术社区  · 9 年前
    [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 回复  |  直到 7 年前
        1
  •  1
  •   Tonci    9 年前

    我不确定你是否需要这些属性 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