I am running some C# Unit Tests in Visual Studio using JSON strings I copied from my database such as:
{
"key" : "Foo",
"format" : "Bar"
}
I want to parse the JSON string to a JObject in my code:
JObject.Parse(
"{
"key" : "Foo",
"format" : "Bar"
}");
However, I can't do this because Visual Studio won't escape the quotes inside the string.
I know I can add escape characters, however, the strings could be very long, which means manually adding the escape characters would take a very long time.
What is the easiest way to parse my copied JSON string into a JObject?
Use verbatim string literals (MSDN) by affixing the string with @. Then replace quotes (") with double quotes ("")
This is much more readable than escaping the quotes using backslash.
JObject.Parse(
@"{
""key"" : ""Foo"",
""format"" : ""Bar""
}");
For my tests with lots of JSON I like to store them in ".json" files embedded into the project DLL.
Note you need a use System.Reflection for this to work.
public string GetFileFromManifest(string path){
using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(path))
{
stream.Position = 0;
using (var streamReader = new StreamReader(stream))
{
return streamReader.ReadToEnd();
}
}
}
Call with the DLL path i.e:
GetFileFromManifest("The.Name.Of.The.Dll.FolderNameOfEmbeddedFiles.Filename.json");
Documentation for GetManifestResourceStream: https://msdn.microsoft.com/en-us/library/xc4235zt(v=vs.110).aspx
Also, you could add the JObject.Parse to this method or create a new method to get it as JSON.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With