c# inserting variable in JSON string by escaping quotes - c#

I have this JSON double quoted string and I want to insert variable idValue
inside
string json = #"
{
""Request"":
{
""ElementList"":
{
""id"": ""idValue""
}
}
}
In regular string this can be done by "+idValue+" ,but how I can do it here when I have
these double quotes? Thanks.

You can do this :
string json = #"
{
""Request"":
{
""ElementList"":
{
""id"": """+ idValue + #"""
}
}
}";
But personally I'd prefer to use a Json library to stringify my stuff.
Edit: Added missing quotation marks in the string.

Related

String builder in c# json problem with \" [duplicate]

This question already has answers here:
C# to JSON serialization using JSON.Net
(2 answers)
Closed 2 months ago.
I created an exaple to demonstrate the problem. I am trying by string builder create a json but there is one problem when the Model.Code contains the \".
If the model value contains double quote json is not valid.
public class Model
{
public string Name { get; set; }
public string Code { get; set; }
}
List<Model> list = new List<Model>();
list.Add(new Model()
{
Name = "Test1",
Code = "124565123"
});
list.Add(new Model() {
Name = "Test2",
Code= "123 \"45"
});
list.Add(new Model()
{
Name = "Test3",
Code = "456"
});
var sb = new StringBuilder();
sb.Append($"\"item_name\":\"{list[0].Name}\",");
sb.Append($"\"item_id\":\"{list[0].Code}\",");
sb.Append($"\"item_name\":\"{list[1].Name}\",");
sb.Append($"\"item_id\":\"{list[1].Code}\",");
sb.Append($"\"item_name\":\"{list[2].Name}\",");
sb.Append($"\"item_id\":\"{list[2].Code}\",");
return sb.ToString();
Add reference to Newtonsoft Json.NET library and serialize the list to json
string json = JsonConvert.SerializeObject(list);
since you are using StringBuilder, " will be Considered as " in the String value just like below
"item_name":"Test1","item_id":"124565123","item_name":"Test2","item_id":"123 "45","item_name":"Test3","item_id":"456",
so , if you want to Convert it to Json , then Json will not Consider value with Double Quote In Between.
Moreover, backslash with double quote ' \" ' suppose to Escape Special Character while Converting to json
I am not sure that you want to Keep that special Character in you Json string If yes then In My Opinion you should try by placing double backslash \\" and Double Quote before your Special Character. and json will Accept it
ex.
\\"45

How to use string interpolation and verbatim string together to create a JSON string literal?

I'm trying to create a string literal representing an array of JSON objects so I thought of using string interpolation feature as shown in the code below:
public static void MyMethod(string abc, int pqr)
{
string p = $"[{{\"Key\":\"{abc}\",\"Value\": {pqr} }}]";
}
Now I thought of using verbatim string so that I don't have to escape double quotes using backslashes. So I came to know through this answer that verbatim string and string interpolation can be used together. So I changed my code as below:
public static void MyMethod(string abc, int pqr)
{
string p = $#"[{{"Key":"{abc}","Value": {pqr} }}]";
}
But it fails to compile. Can anyone help me if there is anything wrong in my usage or it will not be possible to escape double quotes in such a case using string verbatim feature of C#?
The best way is to use JSON serializers as they have in-built handling related to escape characters and other things. See here.
However, if we want to go through this path only to create the JSON string manually, then it can be solved as follows by changing the inner double quotes to single quotes :
public static string MyMethod(string abc, int pqr)
{
string p = $#"[{{'Key':'{ abc}','Value': {pqr} }}]";
return p;
}
I agree with everyone else that building it from strings is a bad idea.
I also understand that you don't want to include an extra dependency.
Here's a bit of code I wrote previously to convert a Dictionary to a JSON string. It's pretty basic, only accepts string types, and doesn't escape quote marks in any of the names/values, but that can be done fairly easily.
If you're trying to serialize a large JSON string from basic types, this is the way I'd recommend to do it. It'll help you stay sane.
private static string DictToJson(Dictionary<string, string> Dict)
{
var json = new StringBuilder();
foreach (var Key in Dict.Keys)
{
if (json.Length != 0)
json = json.Append(",\n");
json.AppendFormat("\"{0}\" : \"{1}\"", Key, Dict[Key]);
}
return "{" + json.ToString() + "}";
}
you can create dictionary and serialize it to json using Json.NET does this.
Dictionary<string, string> values = new Dictionary<string, string>();
values.Add("key1", "value1");
values.Add("key2", "value2");
string json = JsonConvert.SerializeObject(values);
// {
// "key1": "value1",
// "key2": "value2"
// }
you can see here more detail : http://www.newtonsoft.com/json/help/html/SerializingCollections.htm

Convert invalid JSON string with single or no quotes

I have an invalid json string like,
"{StateName: { before: 'AA', after: 'AAA'} },"
Can anyone please help with Regex expression to replace invalid string with valid JSON data? I need to skip the comma at the end & replace single quotes with double quotes or add double quotes where its missing.
Thanks in advance.
Use string.Replace()
jsonString = jsonString.Replace("'", "\"");
jsonString = jsonString.Replace("},", "}");
Simply you use DeserializeObject() on your json string
string json = "{\"StateName\": { "\before\": "\AA\", "\after\": "\AAA\"} }";
and then
object jsondata = JsonConvert.DeserializeObject(json.ToString());

How to read JSON into a JObject when the string contains double quotes ?

I have a piece of JSON that I want to get into a string for C# to use. The problem is when I escape all the double quotes it seems no longer valid. For example:
string jsonString = " {[ { \"FieldId\": \"Fields.364\", \"FieldName\": \"LoanNo\", \"Precision\": \"0\" } , { \"FieldId\": \"Fields.4002\", \"FieldName\": \"LastNameB\" } ]}";
JObject jsettings = JObject.Parse(jsonString);
Is there a easier way to get a string of JSON into a C# JObject?
You're not actually escaping any of the double quotes, as far as the JSON is concerned - the string doesn't contain any backslashes. You can confirm that with Console.WriteLine(jsonString);.
The problem is that you've currently got an array directly inside an object - that's not valid JSON.
If you change it so that the array is a property, it's fine:
string jsonString = " { \"foo\":[ { /* rest as before */ } ] }";
That ended up as JSON of:
{
"foo": [
{
"FieldId": "Fields.364",
"FieldName": "LoanNo",
"Precision": "0"
},
{
"FieldId": "Fields.4002",
"FieldName": "LastNameB"
}
]
}
(Just using Console.WriteLine(jsettings); after the code you'd posted.)

Store Hardcoded JSON string to variable

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": ""
}
}";
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"": """"}}";
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.
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");
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.
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""}";
https://json-to-c-sharp.ndolestudio.com
https://github.com/AchoArnold/json-to-c-sharp
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; }
}
}
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 = ""
}
});
If you are using Visual Studio, then Select the whole JSON string then crtl+f to find the double quotes in the selection and then replace " with ""

Categories