问题
My starting point is something like this (simplified here) :
private object GetPropValue(JToken token, Type type)
{
return JsonConvert.DeserializeObject(token["prop"].ToString(), type);
}
Usage :
var value = GetPropValue(JObject.Parse(someJsonWithAPropertyNamedProp), typeof(someTypeFoundByReflection));
This works, except then the type is string.
According to the doc, ToString() of a JValue should return a JSON, but when the JValue is a type string, the value returned is not a JSON, but rather a simple string, not wrapped with escaped quotes.
Therefore, I get an exception :
An exception of type 'Newtonsoft.Json.JsonReaderException' occurred in Newtonsoft.Json.dll but was not handled in user code
Additional information: Unexpected character encountered while parsing value: s. Path '', line 0, position 0.
What is the best way to achieve this ? Add a condition if the JToken is of type string ?
回答1:
JToken
already has a built-in ToObject()
method to do what you want. If you change your GetPropValue
method to use that instead of converting back and forth from JSON, everything should work fine:
private object GetPropValue(JToken token, Type type)
{
return token["prop"].ToObject(type);
}
来源:https://stackoverflow.com/questions/24042326/parse-json-property-to-a-specific-type