Ticker23
Ticker23

Reputation: 172

Deserializing Json with unexpected characters in property

My application processes a Json that contains a list of objects. The properties of these objects are not completely known to me.

Example, in the following Json, only property "Id" is known to my application:

{"msgs": [
    {
      "Id": "Id1", 
      "A": "AAA"
    },
    {
      "Id": "Id2", 
      "B": "BBB"
    },
    {
      "Id": "Id3", 
      "C": "CCC"
    }
]}

I want to parse these messages and extract the Id of each message. This has been working fine with the following code:

public class RootElem
{

    [BsonElement("msgs")]
    public List<JToken> Records { get; set; }
}

then read

var rootElem = JsonConvert.DeserializeObject<RootElem>(JSON_DATA);

Once I have my rootElem, I can iterate over each record in "Records" and extract the Id.

The problem is that sometime, some of the records will contain unexpected characters.

Example:

{
   "Id": "Id2", 
   "B": "THIS CONTAINS UNEXPECTED DOUBLE QUOTE " WHAT SHOULD I DO?"
}

I tried adding error handling settings, but that didn't work:

var rootElem = JsonConvert.DeserializeObject<RootElem>(data, new JsonSerializerSettings
{
   Error = HandleDeserializationError
});

private static void HandleDeserializationError(object sender, ErrorEventArgs errorArgs)
{
   var currentError = errorArgs.ErrorContext.Error.Message;
   Console.WriteLine(currentError);
   errorArgs.ErrorContext.Handled = true;
}

I want to be able to access the rest of the records in the list, even if one/some of them contain these invalid chars. So I'm ok if "B" value of the 2nd record is return as null, or if the 2nd record is null altogether.

How can I achieve this?

p.s. I'm using Newtonsoft Json but I'm open to using other libraries.

Upvotes: 0

Views: 197

Answers (1)

slorello
slorello

Reputation: 1149

The issue here is that what your application is receiving is not valid JSON, hence the errors you are seeing. The input should be properly escaped prior to being submitted to this method. If this is behind an HTTP API, the appropriate response would be a 400 as the request is not in a valid format. If you really need to work around this it's possible you could implement your own JsonConverter class and decorate the converting class with it, but this may not be possible as the JSON itself is invalid and the JsonReader is going to choke when it hits it.

Upvotes: 1

Related Questions