Parse json property to a specific type

丶灬走出姿态 提交于 2019-12-08 08:19:12

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!