反序列化GUID数组时的JSON.NETexception

我正在使用JSON.NET反序列化从浏览器发送的AJAX HTTP请求,并且遇到使用Guid []作为参数的Web服务调用的问题。 当我使用内置的.NET序列化程序时,这很好用。

首先,流中的原始字节如下所示:

System.Text.Encoding.UTF8.GetString(rawBody); "{\"recipeIds\":[\"d9ede305-d244-483b-a435-abcf350efdb2\"]}" 

然后我打电话给:

 Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer(); parameters[0] = serializer.Deserialize(sr, operation.Messages[0].Body.Parts[0].Type); 

.TypeSystem.Guid[]

然后我得到了例外:

 Cannot deserialize the current JSON object (eg {"name":"value"}) into type 'System.Guid[]' because the type requires a JSON array (eg [1,2,3]) to deserialize correctly. To fix this error either change the JSON to a JSON array (eg [1,2,3]) or change the deserialized type so that it is a normal .NET type (eg not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object. Path 'recipeIds', line 1, position 13. 

采用单个Guid(不是数组)工作的Web服务方法,所以我知道JSON.NET能够将字符串转换为GUID,但是当你有一个要反序列化的字符串数组时它似乎会爆炸到一组GUID。

这是一个JSON.NET错误,有没有办法解决这个问题? 我想我可以编写自己的自定义Guid集合类型,但我不愿意。

你需要一个包装类

 string json = "{\"recipeIds\":[\"d9ede305-d244-483b-a435-abcf350efdb2\"]}"; var obj = JsonConvert.DeserializeObject(json); public class Wrapper { public Guid[] recipeIds; } 

– 编辑 –

使用Linq

 var obj = (JObject)JsonConvert.DeserializeObject(json); var guids = obj["recipeIds"].Children() .Cast() .Select(x => Guid.Parse(x.ToString())) .ToList();