56

I'm having an issue storing this json string to a variable. It's gotta be something stupid I am missing here

private string someJson = @"{
    "ErrorMessage": "",
    "ErrorDetails": {
        "ErrorID": 111,
        "Description": {
            "Short": 0,
            "Verbose": 20
        },
        "ErrorDate": ""
    }
}";
0x9BD0
  • 1,542
  • 18
  • 41
PositiveGuy
  • 46,620
  • 110
  • 305
  • 471

7 Answers7

77

You have to escape the "'s if you use the @ symbol it doesn't allow the \ to be used as an escape after the first ". So the two options are:

don't use the @ and use \ to escape the "

string someJson = "{\"ErrorMessage\": \"\",\"ErrorDetails\": {\"ErrorID\": 111,\"Description\":{\"Short\": 0,\"Verbose\": 20},\"ErrorDate\": \"\"}}";

or use double quotes

string someJson =@"{""ErrorMessage"": """",""ErrorDetails"": {""ErrorID"": 111,""Description"": {""Short"": 0,""Verbose"": 20},""ErrorDate"": """"}}";
Emily
  • 786
  • 6
  • 2
21

First things first, I'll throw this out there: It's for this reason in JSON blobs that I like to use single quotes.

But, much depends on how you're going to declare your string variable.

string jsonBlob = @"{ 'Foo': 'Bar' }";
string otherBlob = @"{ ""Foo"": ""Bar"" }";

...This is an ASCII-encoded string, and it should play nicely with single quotes. You can use the double-double-quote escape sequence to escape the doubles, but a single quote setup is cleaner. Note that \" won't work in this case.

string jsonBlob = "{ 'Foo': 'Bar' }";
string otherBlob = "{ \"Foo\": \"Bar\" }";

...This declaration uses C#'s default string encoding, Unicode. Note that you have to use the slash escape sequence with double quotes - double-doubles will not work - but that singles are unaffected.

From this, you can see that single-quote JSON literals are unaffected by the C# string encoding that is being used. This is why I say that single-quotes are better to use in a hardcoded JSON blob than doubles - they're less work, and more readable.

Blairg23
  • 11,334
  • 6
  • 72
  • 72
Andrew Gray
  • 3,756
  • 3
  • 39
  • 75
  • 12
    Using single quotes is okay and will most likely work but its not a good idea since it is not a part of the JSON standard. The standard calls for double quotes. – Timigen Apr 10 '14 at 20:41
  • 1
    Other platforms and linting tools won't accept single quotes. As an example, jQuery wouldn't parse json with single quotes last time I checked. – gerrard00 Aug 17 '16 at 19:24
  • 2
    @Timigen. The .NET ecosystem itself has come to roost now and the newer `System.Text.Json` library doesn't like single quotes, unlike the older `Newtonsoft.Json` library. – nelsonjchen Aug 13 '20 at 06:08
  • System.Text.Json.JsonReaderException: '''' is an invalid start of a property name. Expected a '"'. – malat Apr 27 '21 at 12:48
10

Simple Approach is to copy the JSON to a .json file and read that file in the code

string jsonData = string.Empty;
jsonData = File.ReadAllText(@"\UISettings.json");
Robert
  • 5,278
  • 43
  • 65
  • 115
Antony david
  • 101
  • 1
  • 2
5

I had this same problem I ended up writing an open source online converter that takes a JSON string and spits out the C# excaped string with the double quotes syntax. So

{ "foo":"bar"}

will be escaped into

var jsonString = @"{ ""foo"":""bar""}";
Arnold Ewin
  • 1,113
  • 1
  • 13
  • 26
4

Writing JSON inline with c# in strings is a bit clunky because of the double quotes required by the JSON standard which need escaping in c# as shown in the other answers. One elegant workaround is to use c# dynamic and JObject from JSON.Net.

dynamic message = new JObject();
message.ErrorMessage = "";
message.ErrorDetails = new JObject();
message.ErrorDetails.ErrorId = 111;
message.ErrorDetails.Description = new JObject();
message.ErrorDetails.Description.Short = 0;

Console.WriteLine(message.ToString());

// Ouputs:
// { 
//   "ErrorMessage": "",
//   "ErrorDetails": {
//     "ErrorID": 111,
//     "Description": {
//       "Short": 0
// .....  

See https://www.newtonsoft.com/json/help/html/CreateJsonDynamic.htm.

alastairtree
  • 3,960
  • 32
  • 49
4

Starting from C# 11 supported on .NET 7, it's possible to embed a JSON string without any modification by enclosing it in triple quote characters, a feature called Raw string literal (learn.microsoft.com). Related useful language feature is StringSyntaxAttribute that allows Visual Studio to recognize the string variable is a JSON string and highlight any typos. A sample:

using System.Diagnostics.CodeAnalysis;
using System.Text.Json;

internal class Program
{
    [StringSyntax(StringSyntaxAttribute.Json)]
    private const string myCountry = """{"Name": "Slovakia", "CountryCode": 421}""";

    private static void Main(string[] args)
    {
        var _ = JsonSerializer.Deserialize<Country>(myCountry);
    }

    class Country
    {
        public string Name { get; set; } = default!;
        public int CountryCode { get; set; }
    }
}
matej bobaly
  • 456
  • 3
  • 6
4

A Put the cart before the horse solution would be to serialize a anonymous class into a string:

var someJson = JsonConvert.SerializeObject(
   new
    {
        ErrorMessage = "",
        ErrorDetails = new
        {
            ErrorID = 111,
            Description = new
            {
                Short = 0,
                Verbose = 20
            },
            ErrorDate = ""
        }
    });
Kraego
  • 2,978
  • 2
  • 22
  • 34