I need to retrieve data from a table stored in SQL server, this table has json string column, then i need to retrieve only rows with a valid json column using linq in C# like that:
var q = from t1 in DBContext.table1 join
t2 in DBContext.table2 on t1.id equals t2.tId
where
//Here what i need to use isJson like that but SqlFunctions does not contain it
SqlFunctions.IsJson(t1.jsonTxt)
select new resDTO
{
name=t1.name,
details =t2.details
}
If I understand correctly you just want to check for a valid Json string in your where clause. In that case you can do this I believe.
var q = from t1 in DBContext.table1 join
t2 in DBContext.table2 on t1.id equals t2.tId
let isValid = IsValidJson(t1.jsonTxt)
where isValid == true
select new resDTO
{
name=t1.name,
details =t2.details
}
private bool IsValidJson(string strInput)
{
if (string.IsNullOrWhiteSpace(strInput)) { return false;}
strInput = strInput.Trim();
if ((strInput.StartsWith("{") && strInput.EndsWith("}")) || //For object
(strInput.StartsWith("[") && strInput.EndsWith("]"))) //For array
{
try
{
var obj = JToken.Parse(strInput);
return true;
}
catch (Exception)
{
return false;
}
}
else
{
return false;
}
}
The method is from this thread: How to make sure that string is valid JSON using JSON.NET
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.