我制作了这样的代码:
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");
使用上面的代码,我成功地使JSON格式如下所示:
{"lon":121,"latt":40.5025,"color":"#3EC1FF"},
现在我的问题是:
如何在不使用c.toString()
的情况下改进字符串格式?
答案 0 :(得分:4)
您可以使用Write
方法的格式重载,例如Write(String, Object[])
这样的事情:
tw.Write("\"color\":\"#{0}\"}},\n", grid.Color.ToString("X").Substring(2));
答案 1 :(得分:0)
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();