首页 > 解决方案 > Newtonsoft.Json.JsonSerializationException:'反序列化对象时出现意外标记:使用动态对象注释

问题描述

我正在尝试使用 Newtonsoft.Json 将 JSON 反序列化为对象。我们的输入 json 请求有注释行。

{
    "paymentMethodToken": "bb3vph6",
    "paymentMethodTypes": "ACH",
    "transactionAmount": "1090.9",
    "transactionType": "Charge",
    "transactionID": "3532464245",
    "merchantAccountID": "643765867",
    "insuredName": "First Last",
    "firstName": "First",
    "lastName": "Last",
    // "sourceUserKey": "example@gmail.com"
    "paymentMethodTokenType": "Durable",
    "paymentType": "Recurring",
    "sourceTransactionId": "OrderACH300"
}

我们想在反序列化时忽略/跳过评论。我相信 Json.Net 默认会这样做。

但我收到错误

Newtonsoft.Json.JsonSerializationException:'反序列化对象时出现意外标记:注释。路径“姓氏”,第 11 行

下面是我用于反序列化的代码

string valueFromBody;
using (var streamReader = new StreamReader(bindingContext.HttpContext.Request.Body))
{
   valueFromBody = streamReader.ReadToEnd();
}

//Deserilaize body content to model instance  
var modelType = bindingContext.ModelMetadata.UnderlyingOrModelType;
var modelInstance = JsonConvert.DeserializeObject(valueFromBody, modelType)

Newtonsoft.Json 版本:12.0.3

模型类

[Serializable]
public class GatewayTransaction : DynamicObject
{
        private CaseInSensitiveDictionary<string, string> customFields = new CaseInSensitiveDictionary<string, string>();

        public string PaymentMethodToken { get; set; }

        public PaymentMethodTypes PaymentMethodTypes { get; set; }

        public string InvoiceId { get; set; }

        public decimal TransactionAmount { get; set; }

        public string ChannelID { get; set; }

        public string TransactionType { get; set; }

        public string TransactionID { get; set; }

        public string MerchantAccountID { get; set; }

        public string InsuredName { get; set; }

        public string FirstName { get; set; }

        public string LastName { get; set; }

        public string SourceUserKey { get; set; }

        public string PaymentMethodTokenType { get; set; }

        public PaymentType PaymentType { get; set; }

        public List<TransactionInfo> PolicyInfo { get; set; }

        public string SourceTransactionId { get; set; }

        [JsonIgnore]
        public CaseInSensitiveDictionary<string, string> CustomFields
        {
            get { return this.customFields; }
        }

        public override bool TryGetMember(GetMemberBinder binder, out object value)
        {
            string stringValue;
            var isFound = this.customFields.TryGetValue(binder.Name, out stringValue);
            value = stringValue;
            return isFound;
        }

        public override bool TrySetMember(SetMemberBinder binder, object value)
        {
            if (value is string)
            {
                this.customFields[binder.Name] = (string)value;
                return true;
            }

            return false;
        }
}

任何帮助,将不胜感激。

标签: c#jsonjson.netasp.net-core-mvcdynamicobject

解决方案


另一种方法是预处理您的 JSON 字符串。在反序列化之前去掉所有注释。你可以做类似的事情

static string StripComments(string code)
{
    var re = @"(@(?:""[^""]*"")+|""(?:[^""\n\\]+|\\.)*""|'(?:[^'\n\\]+|\\.)*')|//.*|/\*(?s:.*?)\*/";
    return Regex.Replace(code, re, "$1");
}

使用上述功能,您可以从 JSON 中去除单行和多行注释。然后进行反序列化。

归因于:从源文件中删除所有注释(单行/多行)和空白行


推荐阅读