10

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?

Philip
  • 3,135
  • 2
  • 29
  • 43
  • 3
    Possible duplicate of [Escape double quotes in string](http://stackoverflow.com/questions/14480724/escape-double-quotes-in-string) – Rob Dec 18 '15 at 12:36
  • If you searched 'C# escape quotes' you would have had your answer. – Rob Dec 18 '15 at 12:36

6 Answers6

25

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""
}");
Peter Henell
  • 2,416
  • 1
  • 17
  • 24
  • 3
    Even better, abuse the json payload a bit: use verbatim strings but replace the double double quotes with single single quotes: `JObject.Parse(@" { 'key' : 'Foo', 'format': 'Bar' } ")` . Not valid Json, but Newtonsoft.Json parses it and it's the most readable version available. – Cristian Diaconescu Dec 27 '20 at 19:29
5

ReSharper does it seamlessly but of course, it costs money.

There's also a free VS extension that does that, here: https://marketplace.visualstudio.com/items?itemName=martinw.SmartPaster2013

Cristian Diaconescu
  • 34,633
  • 32
  • 143
  • 233
  • Thanks for the reminder on SmartPaster... I couldn't remember the name of the extension. This is pretty slick. – TravelDev Dec 23 '20 at 01:52
4

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.

Ben W
  • 76
  • 4
  • As the OP said, he has much longer JSON than just a few lines. This will make managing large chunks more managable (and easier to see errors in the JSON). Obviously using string literals as Peter Henell is the way to go for small chunks – Ben W Dec 18 '15 at 12:58
3

Paste, highlight the selection, Find and Replace " for \"

Steve Harris
  • 5,014
  • 1
  • 10
  • 25
2

Put the JSON in a dedicated .json file in some directory (e.g. TestData/data.json) and load the file contents as a string. Make sure to set the file property of data.json to Copy to output directory.

// File Loader

public static class ReadJsonFile
{
    public static string GetFileFromDisk(string path)
    {
        var absPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
        return File.ReadAllText(absPath + path);
    }
}



// Call the loader
var resultString = ReadJsonFile.GetFileFromDisk("/TestData/data.json");
JObject.Parse(resultString);

This is cleaner and saves you from mingling with large JSON strings. Which can be a pain.

j7nn7k
  • 17,995
  • 19
  • 78
  • 88
0

{ "key" : "Foo", "format" : "Bar" }

Well one thing you can do is use anonyomus objects.

var obj = new { key = "Foo", format = "Bar };
var json = JsonConvert.SerializeObject(obj);
var jsonObject = JsonConvert.DeserializeObject(json);
Rezo Megrelidze
  • 2,877
  • 1
  • 26
  • 29