我必须承认,我可能忘记了一些非常简单的东西,但我弄不清楚是什么。
我有一个类:
public class UserAgentInfo
{
public string agent_type { get; set; }
public string agent_name { get; set; }
public string agent_version { get; set; }
public string os_type { get; set; }
public string os_name { get; set; }
public string os_versionName { get; set; }
public string os_versionNumber { get; set; }
public string linux_distibution { get; set; }
}
然后我从Url获取Json字符串,尝试将其反序列化为:
using (System.Net.WebClient wc = new System.Net.WebClient())
{
string json = wc.DownloadString("http://www.useragentstring.com/?getJSON=agent_type-agent_name-agent_version-os_type-os_name-os_versionName-os_versionNumber-linux_distibution&uas=" + o.Browser);
agentInfo = ServiceStack.Text.TypeSerializer.DeserializeFromString<UserAgentInfo>(json);
}
JSON字符串如下:
"{\"agent_type\":\"Browser\",\"agent_name\":\"Chrome\",\"agent_version\":\"28.0.1500.72\",\"os_type\":\"Windows\",\"os_name\":\"Windows 7\",\"os_versionName\":\"\",\"os_versionNumber\":\"\",\"linux_distibution\":\"Null\"}"
或者对于不习惯使用C#的人来说
"{"agent_type":"Browser","agent_name":"Chrome","agent_version":"28.0.1500.72","os_type":"Windows","os_name":"Windows 7","os_versionName":"","os_versionNumber":"","linux_distibution":"Null"}"
返回的对象是:
{...UserAgentInfo}
agent_name: null
agent_type: null
agent_version: null
linux_distibution: null
os_name: null
os_type: null
os_versionName: null
os_versionNumber: null
我错过了什么?
{"agent_type":"Browser","agent_name":"Chrome",...}
。 - JimmiThC#
中,包含特殊字符(如"
)的字符串必须进行转义,因此需要使用\"
... - balexandre"
开头和结尾,并转义所有其他"
字符,则不会将其解析为JSON对象,而是作为单个JSON字符串。这就是为什么我要问:上面的内容是否确切地是您得到的返回值 - 还是例如Visual Studio调试器显示的内容? - JimmiThjson
的值都不会是你上面写的那样,也永远不会是那样。如果它是,那么这就解释了为什么它无法正确解析。"不习惯C#"是一个大胆的说法。"人们期望你给出字符串的实际值,而不是调试器中的表示"可能更准确。我现在会停止"抱怨"了。 :-) - JimmiTh