反序列化的GUID数组时JSON.NET异常 [英] JSON.NET exception when deserializing an array of GUIDs

查看:1067
本文介绍了反序列化的GUID数组时JSON.NET异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用JSON.NET反序列化从浏览器的AJAX发送HTTP请求,并正在运行成使用GUID []作为参数问题,Web服务调用。这工作得很好,当我用内置的.NET序列化。

I'm using JSON.NET to deserialize AJAX HTTP requests sent in from the browser, and am running into problems with web service calls that use a Guid[] as a parameter. This worked fine when I used the built in .NET serializer.

首先,在流看上去像这样的原始字节:

First off, the raw bytes in the stream look like this:

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

我然后调用:

I then call:

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

。键入的System.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.

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

Web service methods that take in a single Guid (not an array) work, so I know JSON.NET is able to convert a string into a GUID, but it seems to blow up when you have an array of strings that you want to deserialize to an array of GUIDs.

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

Is this a JSON.NET bug, and is there a way to fix this? I suppose I could write my own custom Guid collection type, but I'd rather not.

推荐答案

您需要一个包装类

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();

这篇关于反序列化的GUID数组时JSON.NET异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆