Home >Database >Mysql Tutorial >How to Handle Empty or Null JTokens When Mapping JSON to SQL Parameters in C#?
Checking for Empty or Null JToken in a JObject
Problem:
In a C# application, the following code attempts to loop through a JArray of JObjects and assign values to SQL parameters using the JTokenToSql method. However, if a property in the JObject is empty or null, the JTokenToSql method is not working as expected.
JArray clients = (JArray)clientsParsed["objects"]; foreach (JObject item in clients.Children()) { command.Parameters["@MyParameter"].Value = JTokenToSql(item["thisParameter"]); }
JTokenToSql is defined as:
public static object JTokenToSql(JToken obj) { if (obj.Any()) return (object)obj; else return (object)DBNull.Value; }
Solution:
To check whether a property exists on a JObject, use the square bracket syntax and check if the result is null. If the property exists, a JToken will be returned even if its value is null in the JSON.
JToken token = jObject["param"]; if (token != null) { // the "param" property exists }
To check if a JToken is non-empty, consider using an extension method like the following:
public static class JsonExtensions { public static bool IsNullOrEmpty(this JToken token) { return (token == null) || (token.Type == JTokenType.Array && !token.HasValues) || (token.Type == JTokenType.Object && !token.HasValues) || (token.Type == JTokenType.String && token.ToString() == String.Empty) || (token.Type == JTokenType.Null) || (token.Type == JTokenType.Undefined) } }
This method will return true if the token is null, empty, or of the undefined type.
The above is the detailed content of How to Handle Empty or Null JTokens When Mapping JSON to SQL Parameters in C#?. For more information, please follow other related articles on the PHP Chinese website!