C# preserve escape sequence when reading JSON content using Json.NET
Given the following json text content:
{ "Pattern": "[0-9]*\t[a-z]+" }
Which is reflected in a simple class:
public class Rule
{
public string Pattern { get; set; }
public bool Test(string text)
{
return new Regex(Pattern).IsMatch(text);
}
}
And it's deserialised like this:
var json = System.IO.File.ReadAllText("file.json");
var rule = JsonConvert.DeserializeObject<Rule>(text);
The value of Pattern
is supposed to be a regex pattern. The problem is that, once the content is read, the " \\t
" escape sequence is immediately applied as a escape character which is a tab, resulting in the string value: [0-9]* [az]+
.
What I understand is that the content is somewhat malformed, because it should look like this: [0-9]*\\\\t[az]+
to be valid within the Json content, escaping the backslash so it could be preserved and result into the actual pattern [0-9]*\\t[az]+
. But the file is user edited and I would just like to be able to loosely interpret the content, assuming that backslashes should be preserved (and escape sequences would not be transformed).
I tried to implement a custom JsonConverter
but when looking up the token, the value is already resolved.
I've tried the below code and it works...maybe i don't understand what is the problem or you can provide a sample that doesn't work with this:
StreamReader s= new StreamReader(@"test.txt");
string json = s.ReadToEnd();
json=json.Replace("\\","\\\\");
JObject obj = JObject.Parse(json);
string pattern = obj["Pattern"].ToString();
bool test = Regex.IsMatch("1 a", pattern);
test.txt contains just this:
{ "Pattern": "[0-9]*\t[a-z]+" }
Edit
As Thomasjaworsky remarks, instead of json=json.Replace("\\\\","\\\\\\\\");
is better to use Regex.Replace(json, @"(?<!\\\\)[\\\\](?!\\\\)", @"\\\\")
, it will do the same replace, but only if not already escaped. Two backspaces in row are untouched.
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.