skip to Main Content

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

2

Answers


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

    string json = JsonConvert.SerializeObject(list);
    
    Login or Signup to reply.
  2. 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 
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search