【问题标题】:Newtonsoft.Json.JsonSerializationException: 'Unexpected token when deserializing object: Comment with Dynamic ObjectNewtonsoft.Json.JsonSerializationException:'反序列化对象时出现意外标记:使用动态对象注释
【发布时间】:2023-03-11 11:00:01
【问题描述】:

我正在尝试使用 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"
}

我们想在反序列化时忽略/跳过 cmets。我相信 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;
        }
}

任何帮助将不胜感激。

【问题讨论】:

  • @Sergey 它只是测试数据,您可以忽略,但问题在于注释行。有了这个我无法反序列化
  • 更正开发人员说它确实支持多行 /**/ 和单行注释 // 和 stackoverflow.com/a/10325432/6560478
  • @DragandDrop 得到了一点,我尝试用一​​个非常简单的例子重现这个,只要你将 cmets 引入 json。 Newtonsoft 反序列化失败,建议你在反序列化之前从 json 中删除 cmets
  • github上应该有单元测试。如果没有,您可以创建一个问题并提出建议。
  • @JochemVanHespen 如果我们删除它就可以工作。我想看到的只是忽略注释行(如果存在)

标签: c# json json.net asp.net-core-mvc dynamicobject


【解决方案1】:

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

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

使用上述函数,您可以从 JSON 中去除单行和多行 cmets。 然后进行反序列化。

归因于:Remove all comment (single-/multi-line) & blank lines from source file

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多