59

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": ""
    }
}";
11
  • 8
    Replace " with "" in the content Commented Apr 10, 2014 at 20:19
  • 9
    I think you just drank too much coffee... we've all been there... Commented Apr 10, 2014 at 20:21
  • 1
    And here's the relevant part of the friendly manual for good measure: msdn.microsoft.com/en-us/library/362314fe.aspx Commented Apr 10, 2014 at 20:21
  • 1
    @CoffeeAddict the @ symbol escapes everything with the exception of the quote escape sequence: msdn.microsoft.com/en-us/library/aa691090(v=vs.71).aspx Commented Apr 10, 2014 at 20:27
  • 1
    @Clark, I was thinking what verdesrobert was, that it's not JS but you know what? I'm storing it as JSON so it's fine to have single quotes I think. I'm not sure if the JavascriptSerializer cares when it attempts to deserialize it with single quotes, haven't tried, maybe it doesn't matter Commented Apr 10, 2014 at 20:28

8 Answers 8

82

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"": """"}}";
Sign up to request clarification or add additional context in comments.

3 Comments

best way is to use Json.net check this
yes, the simplest way just convert online tools.knowledgewalls.com/jsontostring
I Also wrote a converter that uses the double quotes syntax to escape JSON strings in c# json-to-c-sharp.ndolestudio.com
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.

4 Comments

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.
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.
@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.
System.Text.Json.JsonReaderException: '''' is an invalid start of a property name. Expected a '"'.
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");

Comments

8

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 = ""
        }
    });

Comments

7

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; }
    }
}

Comments

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""}";

1 Comment

This worked great for a good-sized set of test data - thanks for sharing
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.

Comments

2

in C# 11 Raw string literals are introduced and you can easily define multi-line strings with triple quota like this:

var jsonValue = 
"""
{
    "ErrorMessage": "",
    "ErrorDetails": {
        "ErrorID": 111,
        "Description": {
            "Short": 0,
            "Verbose": 20
        },
        "ErrorDate": ""
    }
}
"""

it keeps string format and with $$ before string you can use string combinations like this:

var location = $$"""
   You are at {{{Longitude}}, {{Latitude}}}
""";

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.