解析JSON属性的特定类型 [英] Parse json property to a specific type

查看:593
本文介绍了解析JSON属性的特定类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的出发点是这样的(这里的简化):

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.

据商务部,的ToString(一JValue的)应该返回一个JSON,但当JValue是一种类型的字符串,返回的值是不是一个JSON ,而是一个简单的字符串,而不是包裹转义引号

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 :

类型的异常Newtonsoft.Json.JsonReaderException发生在
Newtonsoft.Json.dll但在用户代码

An exception of type 'Newtonsoft.Json.JsonReaderException' occurred in Newtonsoft.Json.dll but was not handled in user code

更多信息:分析
值遇到意外字符:秒。路径',0行,位置0。

Additional information: Unexpected character encountered while parsing value: s. Path '', line 0, position 0.

什么是实现这一目标的最佳途径?添加一个条件,如果JToken是字符串类型的?

What is the best way to achieve this ? Add a condition if the JToken is of type string ?

推荐答案

JToken 已经有一个内置的 ToObject()方法去做你想做的。如果你改变你的 GetPropValue 方法来使用,而不是转换从JSON来回的,一切都应该很好地工作:

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);
}

这篇关于解析JSON属性的特定类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆