【问题标题】:JSON.NET exception when deserializing an array of GUIDs反序列化 GUID 数组时出现 JSON.NET 异常
【发布时间】:2012-11-30 15:11:19
【问题描述】:

我正在使用 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 集合类型,但我不想这样做。

【问题讨论】:

    标签: c# .net json.net deserialization


    【解决方案1】:

    你需要一个包装类

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

    【讨论】:

    • 那么这是一个 JSON.NET 错误。
    • @MikeChristensen 不,请参阅您的 json 中的 recipeIds。你得到一个对象,它的属性 recipeIds 包含 Guid 数组。
    • 你是对的。这个序列化程序实际上工作得很好,它是这个用于 JSON.NET 的 WCF 格式化程序有错误。我需要重新处理一些逻辑。
    • 但是从好的方面来说,你达到了 30k 代表,因为当我应该去睡觉的时候,我在 StackOverflow 上问愚蠢的问题..
    猜你喜欢
    • 2013-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-23
    • 1970-01-01
    • 1970-01-01
    • 2015-12-09
    • 2015-05-06
    相关资源
    最近更新 更多