In my application I'm using newtonsoft to serialize and deserialize object, I want to know is there any built in API to determine that input string can deserialize to specific object or not?
public TObject Deserialize<TObject>(string serialized)
{
/// I want check the condition, and if is not serialized string just return default(TObject)
return JsonConvert.DeserializeObject<TObject>(serialized);
}
I don't want to use try catch
. Currently I implemented like that but looking to find a way to verify the string before start to deserialize object.
Already I saw this question Deserialize json in a "TryParse" way, but its not my answer cause I don't have any specific schema and JSON format can change dynamically.
Then, to deserialize from a string or a file, call the JsonSerializer. Deserialize method. For the generic overloads, you pass the type of the class you created as the generic type parameter. For the non-generic overloads, you pass the type of the class you created as a method parameter.
The simplest way to check if JSON is valid is to load the JSON into a JObject or JArray and then use the IsValid(JToken, JSchema) method with the JSON Schema. To get validation error messages use the IsValid(JToken, JSchema, IList<String> ) or Validate(JToken, JSchema, SchemaValidationEventHandler) overloads.
Serialization and deserialization in . NET application, JSON data format conversion to . NET objects and vice versa is very common. Serialization is the process of converting . NET objects such as strings into a JSON format and deserialization is the process of converting JSON data into . NET objects.
Deserialization is the process of reversing a String from a previously serialized format. This coverts the serialized String into a format that allows its Data Structure properties to be accessible to manipulation.
There is no TryParse
in Json.Net as of the current release. If you don't have a known schema to validate against, and you don't want to use try...catch
then your only other option that I can see is to attach an error handler to the serializer and use that as a means of detecting and/or handling errors. See "Error Handling" in the documentation.
private static bool TryParseJSON(string json, out JObject jObject)
{
try
{
jObject = JObject.Parse(json);
return true;
}
catch
{
jObject = null;
return false;
}
}
worked just fine for my scenario
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With