csharp JSON.NET:JObject扩展方法

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp JSON.NET:JObject扩展方法相关的知识,希望对你有一定的参考价值。

/// <summary>
/// Extensions of <see cref="JObject"/>
/// </summary>
public static class JObjectExtensions
{
    /// <summary>
    /// Gets the <see cref="JArray"/>.
    /// </summary>
    /// <param name="jsonObject">The json object.</param>
    /// <param name="arrayPropertyName">Name of the array property.</param>
    /// <returns></returns>
    /// <exception cref="System.ArgumentNullException">arrayPropertyName;The expected JArray Property Name is not here.</exception>
    /// <exception cref="System.FormatException">
    /// </exception>
    public static JArray GetJArray(this JObject jsonObject, string arrayPropertyName)
    {
        if (jsonObject == null) return null;
        if (string.IsNullOrEmpty(arrayPropertyName)) throw new ArgumentNullException("arrayPropertyName", "The expected JArray Property Name is not here.");

        var jO = jsonObject[arrayPropertyName];
        if (jO == null) throw new FormatException(string.Format("The expected property name “{0}” is not here.", arrayPropertyName));

        var jsonArray = JArray.FromObject(jO);
        if (!jsonArray.Any()) throw new FormatException(string.Format("The array “{0}” is not here.", arrayPropertyName));

        return jsonArray;
    }

    /// <summary>
    /// Gets the <see cref="JToken"/> from <see cref="JArray"/>.
    /// </summary>
    /// <param name="jsonObject">The json object.</param>
    /// <param name="arrayPropertyName">Name of the array property.</param>
    /// <param name="objectPropertyName">Name of the object property.</param>
    /// <param name="arrayIndex">Index of the array.</param>
    /// <returns></returns>
    /// <exception cref="System.ArgumentNullException">objectPropertyName;The expected JObject Property Name is not here.</exception>
    public static JToken GetJTokenFromJArray(this JObject jsonObject, string arrayPropertyName, string objectPropertyName, int arrayIndex)
    {
        var jsonArray = jsonObject.GetJArray(arrayPropertyName);

        if (string.IsNullOrEmpty(objectPropertyName)) throw new ArgumentNullException("objectPropertyName", "The expected JObject Property Name is not here.");

        var jsonToken = jsonArray[arrayIndex];
        return jsonToken[objectPropertyName];
    }
}

以上是关于csharp JSON.NET:JObject扩展方法的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 json.net 将 json 数组添加到 JObject 的属性中

如何将 Dictionary<string,string> 添加到现有 JSON.Net 的 JObject?

REST API 包装器设计:将动态 json 作为 JSON.NET JObject / JArray 返回

csharp JObject JArray多选的测试

csharp JArray JObject JToken

使用 JObject 修改集合中的 JSON 字段