DataMember 连接成逗号分隔的字符串
DataMember being concatenated into comma separated string
[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"
}
我不确定 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
[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"
}
我不确定 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