DataContractJsonSerializer 抛出异常 - 值不能为 null。 (参数“键”)

问题描述 投票:0回答:1

我有一个 JSON 字符串,我想反序列化为

Microsoft.Xrm.Sdk.Entity
对象:

{
    "Id": "28bdb958-71fd-e711-8129-5065f38be461",
    "Name": "name",
    "Attributes": [
        { "Key": "key1", "Value": "value1" },
        { "Key": "key2", "Value": "value2" }
    ]
}

当我有以下代码尝试解析上面的 JSON 字符串时(让我们将其命名为

jsonString
):

using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;
using Microsoft.Xrm.Sdk;

var serializer = new DataContractJsonSerializer(typeof(Entity));
using var stream = new MemoryStream(Encoding.ASCII.GetBytes(jsonString));
var entity = serializer.ReadObject(stream) as Entity;

它抛出异常:

Unhandled exception. System.ArgumentNullException: Value cannot be null. (Parameter 'key')
   at System.Collections.Generic.Dictionary`2.TryInsert(TKey key, TValue value, InsertionBehavior behavior)
   at System.Collections.Generic.Dictionary`2.System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>.Add(KeyValuePair`2 keyValuePair)
   at ReadAttributeCollectionFromJson(XmlReaderDelegator , XmlObjectSerializerReadContextComplexJson , XmlDictionaryString , XmlDictionaryString , CollectionDataContract )
   at System.Runtime.Serialization.Json.JsonCollectionDataContract.ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context)
   at System.Runtime.Serialization.Json.JsonDataContract.ReadJsonValue(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context)
   at System.Runtime.Serialization.Json.XmlObjectSerializerReadContextComplexJson.ReadDataContractValue(DataContract dataContract, XmlReaderDelegator reader)
   at System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(XmlReaderDelegator reader, String name, String ns, Type declaredType, DataContract& dataContract)
   at ReadEntityFromJson(XmlReaderDelegator , XmlObjectSerializerReadContextComplexJson , XmlDictionaryString , XmlDictionaryString[] )

我安装的Dataverse NuGet包是Microsoft.PowerPlatform.Dataverse.Client,版本1.0.1。

c# asp.net-core dynamics-crm
1个回答
0
投票

我对自己的问题有一个解决方案,但我仍然不明白为什么/如何/什么?!

解决方案是使用小写

key
value
而不是大写?!

{
    "Id": "28bdb958-71fd-e711-8129-5065f38be461",
    "Name": "name",
    "Attributes": [
        { "key": "key1", "value": "value1" },
        { "key": "key2", "value": "value2" }
    ]
}

大写:https://dotnetfiddle.net/lm2gj7 - 不工作

小写:https://dotnetfiddle.net/sbEJyl - 正在工作!

我花了一天时间才弄清楚这个问题!

© www.soinside.com 2019 - 2024. All rights reserved.