1

Fairly new to C# and I'm trying to build a clean-ish multi line string using a verbatim string literal, but also trying to pass in variables to it.

Says it is not formatted correctly, so seeing what I am doing wrong here, as this format is close to what I've seen in other SO questions.

  var bodyJson =string.Format(@"{
                                  ""[email protected]"": ""/consultingprojectses({0})"",
                                  ""[email protected]"": ""products(f4b6b505-99df-e711-8108-c4346bdc3201)"",
                                  ""[email protected]"": ""/contacts({1})"",
                                  ""[email protected]"": ""/accounts({2})""
                                }", projectRecord.consultingprojectsid, contact, projectRecord.account_value);

Or preferably this:

  var bodyJson =string.Format(@"{
                                  '[email protected]': '/consultingprojectses({0})',
                                  '[email protected]': 'products(f4b6b505-99df-e711-8108-c4346bdc3201)',
                                  '[email protected]': '/contacts({1})',
                                  '[email protected]': '/accounts({2})'
                                }", projectRecord.consultingprojectsid, contact, projectRecord.account_value);
6
  • 4
    JSON is serialized data from a model or object; rather than concocting a fancy string use a serializer Commented Aug 13, 2019 at 20:37
  • 2
    You have to escape the { and }. How to escape braces (curly brackets) in a format string in .NET Commented Aug 13, 2019 at 20:37
  • 2
    Please don't do this. Create an object and use a serializer! Commented Aug 13, 2019 at 20:40
  • You may want to consider using JObject to create the necessary structure and values rather than trying to escape and all that; for instance, technically you have invalid JSON because strings must use double quotes, not single quotes. Commented Aug 13, 2019 at 20:42
  • Why not try replace by placing some place holder like bodyJson.Replace("{0}","myvalue") Commented Aug 13, 2019 at 20:43

1 Answer 1

2

Create an object and use a serializer to construct your Json:

var obj = new
            {
                Key1 = "value1",
                Key2 = "value2"
            };

var json = JsonConvert.SerializeObject(obj);
Sign up to request clarification or add additional context in comments.

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.