0

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();
3
  • In general, you need to handle escaping of special characters, like ". Commented Dec 21, 2022 at 13:14
  • 4
    What's wrong with using System.Text.Json? Commented Dec 21, 2022 at 13:15
  • Why build the JSON like this instead of simply serialize the list? Commented Dec 21, 2022 at 13:16

2 Answers 2

2

Add reference to Newtonsoft Json.NET library and serialize the list to json

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

Comments

0

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 

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.