且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

JSON.NET:从JProperty值获取JObject

更新时间:2023-01-17 22:55:55

获取JProperty(即JToken)的Value,并查看其Type.此属性将告诉您令牌是否为对象,数组,字符串等.如果令牌类型为对象,则只需将其强制转换为JObject并将其传递给函数即可.如果令牌类型不是对象,并且您的函数必须具有JObject,那么您需要将值包装在JObject中才能使其正常工作.

Get the Value of the JProperty, which is a JToken, and look at its Type. This property will tell you if the token is an Object, Array, String, etc. If the token type is Object, then you can simply cast it to a JObject and pass it to your function. If the token type is something other than Object and your function has to have a JObject, then you'll need to wrap the value in a JObject in order to make it work.

foreach (JProperty jsonRootProperty in jsonObject.Properties())
{    
    if (jsonRootProperty.Name=="Hotel")
    {
        JToken value = jsonRootProperty.Value;
        if (value.Type == JTokenType.Object)
        {
            FunctionThatAcceptsJObject((JObject)value);
        }
        else
        {
            FunctionThatAcceptsJObject(new JObject(new JProperty("value", value)));
        }
    }
}