I am parsing tons of different jsons which only have the first Property in common.
Depending on the value of this first property I parse the json into different object and also handle possible error differently. However it happens that the json is not valid but I still want to know the value of the first property (as long as this is valid) so I can handle the parsing error. I was wondering if this is possible with Json.Net
. Of course I assume that at least the first property is valid, something like this for example:
{
"parsingType":"sometype",
"someothervalue":123,
"someval"123,
}
I tried the following but since the exception is thrown when using .Parse
I get no result:
JToken jtoken = JToken.Parse(json);
var theValueIWantToGet = jtoken["parsingType"].Value<string>();
You can use a JsonReader
(probably JsonTextReader
as the concrete type) to parse the JSON as a stream, a bit like XmlReader
. So for example:
using System;
using System.IO;
using Newtonsoft.Json;
public class Test
{
static void Main(string[] args)
{
using (var reader = new JsonTextReader(File.OpenText("test.json")))
{
while (reader.Read())
{
Console.WriteLine(reader.TokenType);
Console.WriteLine(reader.Value);
}
}
}
}
On the JSON you've provided, that will give output of:
StartObject
PropertyName
parsingType
String
sometype
PropertyName
someothervalue
Integer
123
Unhandled Exception: Newtonsoft.Json.JsonReaderException [...]
So if you always expect there to be a start object, then a property name, then a string property value, you could easily validate that that's the case and extract the property value.
See more on this question at Stackoverflow