3

我正在使用 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 (e.g. {"name":"value"}) into type 'System.Guid[]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.

To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) 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 集合类型,但我不想这样做。

4

1 回答 1

5

你需要一个包装类

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


public class Wrapper
{
    public Guid[] recipeIds;
}

- 编辑 -

使用 Linq

var obj = (JObject)JsonConvert.DeserializeObject(json);

var guids = obj["recipeIds"].Children()
            .Cast<JValue>()
            .Select(x => Guid.Parse(x.ToString()))
            .ToList();
于 2012-11-30T07:04:18.217 回答