I am trying to deserialize the JSON to a object using Newtonsoft.Json. Our input json request has commented line.

{
    "paymentMethodToken": "bb3vph6",
    "paymentMethodTypes": "ACH",
    "transactionAmount": "1090.9",
    "transactionType": "Charge",
    "transactionID": "3532464245",
    "merchantAccountID": "643765867",
    "insuredName": "First Last",
    "firstName": "First",
    "lastName": "Last",
    // "sourceUserKey": "[email protected]"
    "paymentMethodTokenType": "Durable",
    "paymentType": "Recurring",
    "sourceTransactionId": "OrderACH300"
}

we wanted to ignore/skip the comments while deserializing. I believe Json.Net does this by default.

But I am getting error as

Newtonsoft.Json.JsonSerializationException: 'Unexpected token when deserializing object: Comment. Path 'lastName', line 11

Below is the code I am using for deserialization

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 Version: 12.0.3

Model Class

[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;
        }
}

Any help would be appreciated.

1

There are 1 answers

2
Alen Smith On

A different approach is preprocess your JSON string. Strip out all the comments before de-serializing. You could do something like

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

Using the above function, You can strip out single and multiline comments from JSON. Then do de-serializing.

Attributed to: Remove all comment (single-/multi-line) & blank lines from source file