Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store Hardcoded JSON string to variable

Tags:

json

c#

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": ""     } }"; 
like image 431
PositiveGuy Avatar asked Apr 10 '14 20:04

PositiveGuy


People also ask

Can we store JSON in string?

Even though JSON was derived from JavaScript, it is a platform-independent format. You can work with it in multiple programming languages including Java, Python, Ruby, and many more. Really, any language that can parse a string can handle JSON.

What is [] and {} in JSON?

' { } ' used for Object and ' [] ' is used for Array in json.

How do I convert a JSON to a string?

Use the JavaScript function JSON. stringify() to convert it into a string. const myJSON = JSON. stringify(obj);

Does JSON dumps convert to string?

dumps() json. dumps() function converts a Python object into a json string.


2 Answers

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"": """"}}"; 
like image 164
Emily Avatar answered Sep 20 '22 18:09

Emily


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.

like image 44
Andrew Gray Avatar answered Sep 20 '22 18:09

Andrew Gray