Skip to content

Instantly share code, notes, and snippets.

@BryanWilhite
Created January 7, 2016 00:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save BryanWilhite/481709d432ad2c3e4758 to your computer and use it in GitHub Desktop.
Save BryanWilhite/481709d432ad2c3e4758 to your computer and use it in GitHub Desktop.
JSON.NET: JObject extension methods
/// <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