我目前正在从事WinRT应用程序和API自服务,该服务似乎很好。Json转换列表铸造错误
我正在使用json来传输我的数据。我没有问题序列化我想要传输的类的实例,但问题出现时,我想解串器。
这里的类:
public class DtoDirectory
{
public string Name { get; set; }
public string Path { get; set; }
public List<string> DirectoryIcon { get; set; }
}
这里是我写操纵JSON
public class SerializeHelper
{
public static T Deserialize<T>(string value) where T : class
{
try
{
var ret = JsonConvert.DeserializeObject<T>(value);
return ret;
}
catch(Exception e)
{
return null;
}
}
public static string Serialize<T>(T type) where T : class
{
try
{
var output = JsonConvert.SerializeObject(type);
return output;
}
catch (Exception)
{
return null;
}
}
}
这里的数据时,它来自API的帮助:
"[{"Name":"ANNONCES LEGALES","Path":"C:\\Test\\ANNONCES LEGALES","DirectoryIcon":["C:\\Test\\ANNONCES LEGALES\\fond.png","C:\\Test\\ANNONCES LEGALES\\icon.png"]},{"Name":"CONSEIL MUNICIPAL","Path":"C:\\Test\\CONSEIL MUNICIPAL","DirectoryIcon":["C:\\Test\\CONSEIL MUNICIPAL\\fond.png","C:\\Test\\CONSEIL MUNICIPAL\\icon.png"]},{"Name":"DIVERS","Path":"C:\\Test\\DIVERS","DirectoryIcon":["C:\\Test\\DIVERS\\fond.png","C:\\Test\\DIVERS\\icon.png"]},{"Name":"ELECTIONS","Path":"C:\\Test\\ELECTIONS","DirectoryIcon":["C:\\Test\\ELECTIONS\\fond.png","C:\\Test\\ELECTIONS\\icon.png"]},{"Name":"ETAT CIVIL","Path":"C:\\Test\\ETAT CIVIL","DirectoryIcon":["C:\\Test\\ETAT CIVIL\\fond.png","C:\\Test\\ETAT CIVIL\\icon.png"]},{"Name":"URBANISME","Path":"C:\\Test\\URBANISME","DirectoryIcon":["C:\\Test\\URBANISME\\fond.png","C:\\Test\\URBANISME\\icon.png"]}]"
最后的错误:
{"Could not cast or convert from System.String to System.Collections.Generic.IList`1[DTO.DtoDirectory]."}
Error converting value to type 'System.Collections.Generic.IList`1[DTO.DtoDirectory]'. Path '', line 1, position 1027.
编辑:
这里我所说的解串器的代码:
try
{
var client = new HttpClient();
var uri = new Uri("http://localhost:1234/api/document/ListDirectoryRoot?pathDirecory=C:\\Test\\Chasse");
var request = new HttpRequestMessage(HttpMethod.Get, uri);
var res = await client.SendAsync(request);
var content = await res.Content.ReadAsStringAsync();
var test = SerializeHelper.Deserialize<Wrapper >(lol);
return content;
}
catch (Exception)
{
return null;
}
public class Wrapper
{
public List<DtoDirectory> list {get;set;}
}
我很遗憾没有成功找出错误.. 感谢您的帮助!
您可以在您的问题中添加实际使用/调用SerializeHelper方法的代码吗? – 2014-10-06 09:02:39
什么是“包装”?你能不能也请发贴'Wrapper'类。 – Michael 2014-10-06 09:08:21
我做了更改;) – bottus 2014-10-06 09:11:33