What is the better way to string format a double quote if the element inside the quote is a variable?

StackOverflow https://stackoverflow.com/questions/20899895

  •  23-09-2022
  •  | 
  •  

Question

I have made a code like this:

TextWriter tw = File.CreateText(@"D:\output.txt");

tw.Write(@"{""lon"":" + grid.point[0].ToString("###.####") + ",");
tw.Write(@"""latt"":" + grid.point[1].ToString("###.####") + ",");

char c = '"';
////improve the last line pls 
tw.Write(@"""color"":" + c.ToString() + "#" + grid.Color.ToString("X").Substring(2) + c.ToString() + "},\n"); 

With the above code, I had successfully made a JSON format look like below:

{"lon":121,"latt":40.5025,"color":"#3EC1FF"},

Now My question is: How to improve the string format without using the c.toString()?

Was it helpful?

Solution

You can use the format overload of the Write method e.g. Write(String, Object[]).

Something like this:

tw.Write("\"color\":\"#{0}\"}},\n", grid.Color.ToString("X").Substring(2));

OTHER TIPS

StringBuilder jsonBuilder=new StringBuilder();
 jsonBuilder.AppendFormat("{0}", "{");

 jsonBuilder.AppendFormat("\"Lat\":{0:0.000},", 584.25689);
 jsonBuilder.AppendFormat("\"Lon\":{0:0.000},", 784.25689);


 jsonBuilder.AppendFormat("Color:{0}","\"#3EC1FF\"");
 jsonBuilder.AppendFormat("{0}", "}");

  string json = jsonBuilder.ToString();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top