JTokenExtensions.cs
1.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Text;
namespace Contentful.Core.Extensions
{
/// <summary>
/// Extensionmethods for JToken
/// </summary>
public static class JTokenExtensions
{
/// <summary>
/// Checks whether a JToken is null or of null type.
/// </summary>
/// <param name="token">The token to validate.</param>
/// <returns>Whether the token is null or not.</returns>
public static bool IsNull(this JToken token)
{
return token == null || token.Type == JTokenType.Null;
}
/// <summary>
/// Returns an int value from a JToken.
/// </summary>
/// <param name="token">The token to retrieve a value from.</param>
/// <returns>The int value.</returns>
public static int ToInt(this JToken token)
{
if (token.IsNull())
{
return 0;
}
return int.Parse(token.ToString());
}
/// <summary>
/// Returns a nullable int value from a JToken.
/// </summary>
/// <param name="token">The token to retrieve a value from.</param>
/// <returns>The nullable int value.</returns>
public static int? ToNullableInt(this JToken token)
{
if (token.IsNull())
{
return new int?();
}
return new int?(token.ToInt());
}
}
}