-1

Am getting json formatted string which is stored in database, now i want to convert it into json format. How can i convert it Please help.

 var labelnames = @"{'LabelName':'LabelName1','IsHeader':true},{'LabelName':'LabelName2','IsHeader':false},{'LabelName':'LabelName3','IsHeader':true},{'LabelName':'LabelName4','IsHeader':false}";

I want to convert above code to proper json format

Surya
  • 265
  • 1
  • 3
  • 10
  • Does this answer your question? [Convert JSON String to JSON Object c#](https://stackoverflow.com/questions/22870624/convert-json-string-to-json-object-c-sharp) – 777moneymaker Aug 17 '21 at 12:12
  • 3
    `labelnames = "[" + labelnames.Replace("'", "\"") + "]"` looks like it should do the trick – Charlieface Aug 17 '21 at 12:12
  • 1
    Huh? You have "a json formatted string" but you want to "convert it into json format"? – gunr2171 Aug 17 '21 at 12:12
  • 2
    That is not a JSON formatted string that you're getting from the database! – phuzi Aug 17 '21 at 12:13
  • Now is probably also a good time to correct whatever is the *source* of this data so that it gets saved to the DB in JSON format to begin with, which would make this problem moot. – David Aug 17 '21 at 12:18

1 Answers1

-1

This is an invalid JSON format, moreover it does not have surrounding array brackets []. Ideally you should fix this at source.

You could do a simple replace

MyLabels = JsonConvert.DeserializeObject<List<Label>>(labelnames = "[" + labelnames.Replace("'", "\"") + "]")

However this may throw an error if any of the values also contain a '.

Therefore, you could create a custom JsonTextReader

        using (var sw = new StringReader("[" + labelnames + "]"))
        using (var reader = new MyJsonTextReader(sw))
        {
            JsonSerializer ser = new JsonSerializer();
            MyLabels = ser.Deserialize<List<Label>>(reader);
        }
    class MyJsonTextReader : JsonTextReader
    {
        public override char QuoteChar { get; protected set; } = '\'';
        
        public MyJsonTextReader(TextReader r) : base(r){}
    }
    class Label
    {
        public string LabelName;
        public bool IsHeader;
    }

dotnetfiddle

Charlieface
  • 52,284
  • 6
  • 19
  • 43