通过使用下面的代码我调用api并尝试反序列化。我已经将字符串替换为json格式,如下所示,
//从api获取字符串响应的代码
var client = new WebClient();
client.Credentials = new NetworkCredential(userName, passWord);
client.Headers.Add(headerKey, headerValue);
client.QueryString.Add("companynumber", companyNumber);
var response = client.DownloadString(customerAPI);
response = response.Replace("\"", "").Replace("\\", "\"");
var results = JsonConvert.DeserializeObject<List<ProjectResponse>>(response);
输出json结果
“\”[{\\ “数据\\”:{\\ “封闭\\”:假,\\ “companynumber \\”:\\ “430 \\”,\\ “CUSTOMERNUMBER \\” :\\ “430 \\\\” INTERNAL \\ “}},{\\” 数据\\ “:{\\” 封闭\\ “:假,\\” companynumber \\ “:\\” 430 \ \ “\\ ”CUSTOMERNUMBER \\“:\\ ”430INTERNAL \\“}}]”
相应的反序列化类在下面,
public class Project
{
public Nullable<long> CompanyNumber { get; set; }
public string CustomerNumber { get; set; }
public bool Closed { get; set; }
}
public class ProjectResponse
{
public Project data { get; set; }
}
在这个例子中我得到两个列表,在第一个customernumber中有\\“430 \\\\”INTERNAL \\双引号和反斜杠值所以这不允许我反序列化到我各自的类。所以如何反序列化字符串eventHough其中一列中有双引号。
答案 0 :(得分:1)
代码已被序列化两次。模型被序列化为JSON,然后再次序列化JSON字符串。
要解决此问题,您需要反过来。
var response = client.DownloadString(customerAPI);
var json = JsonConver.DeserializeObject<string>(response);
var projects = JsonConvert.SeseializeObject<List<ProjectResponse>>(json);