-
-
Save iamsingularity/c1c19c1d775bca8739e2f0a359e28124 to your computer and use it in GitHub Desktop.
JSON.NET: JObject extension methods
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <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]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment