Home > Enterprise >  String builder in c# json problem with \"
String builder in c# json problem with \"

Time:12-22

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();

CodePudding user response:

use newtonsoft json and serialize the list to json

string json = JsonConvert.SerializeObject(list);

CodePudding user response:

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 
  • Related