Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Paste JSON string into Visual Studio

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?

like image 289
Philip Bergström Avatar asked Dec 18 '15 12:12

Philip Bergström


2 Answers

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""
}");
like image 172
Peter Henell Avatar answered Sep 23 '22 11:09

Peter Henell


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.

like image 41
Ben W Avatar answered Sep 25 '22 11:09

Ben W