4

Is there way to deserialize invalid json?

For example, next JSON deserialization will fail with JsonReaderException

{
 'sessionId': 's0j1',
 'commandId': 19,
 'options': invalidValue // invalid value
}

because options property value is invalid.

Is there a nice way to get sessionId and commandId values even if options value is invalid?

I know it's possible to handle errors during deserialization (http://www.newtonsoft.com/json/help/html/SerializationErrorHandling.htm)

var json = "{'sessionId': 's0j1', 'commandId': 19, 'options': invalidValue}"; 

var settings = new JsonSerializerSettings
{
    Error = delegate(object sender, ErrorEventArgs args)
    {
      args.ErrorContext.Handled = true;
    }
});
var result = JsonConvert.DeserializeObject(json, settings);

Bit it will result in result = null.

1
  • I don't think Json.NET can handle invalid Json. If you want to parse something that is not Json, have a look at this answer Commented Sep 8, 2016 at 6:48

1 Answer 1

4

You can do it with JsonReader.

Example code:

var result = new Dictionary<string, object>();

using (var reader = new JsonTextReader(new StringReader(yourJsonString)))
{
    var lastProp = string.Empty;
    try
    {
        while (reader.Read())
        {
            if (reader.TokenType == JsonToken.PropertyName)
            {
                lastProp = reader.Value.ToString();
            }

            if (reader.TokenType == JsonToken.Integer || 
                reader.TokenType == JsonToken.String)
            {
                result.Add(lastProp, reader.Value);
            }
        }
    }

    catch(JsonReaderException jre)
    {
        //do anything what you want with exception
    }
}

Note, that there is try..catch block as when JsonReader meets invalid character it throws JsonReaderException on reader.Read()

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.