0

I'm implementing a customize toJson() method.

One of my class member is a dictionary.

I did :

        sb.Append("\"DateSource\" : {");
        foreach (var row in DateSource)
        {
            sb.Append("[");
            sb.Append(string.Format("\"RowKey\" : {0}", row.Key));
            sb.Append(string.Format("\"RowData\" : {0}", row.Value));
            sb.Append("]");
        }
        sb.Append("}");

How can I avoid the last comma in the conversion ?

Elad Benda
  • 35,076
  • 87
  • 265
  • 471

4 Answers4

6

You can use:

sb.Append("[");
sb.Append(string.Join(
    ", ",
    DateSource.Select(r => string.Format("\"RowKey\" : {0}, \"RowData\" : {1}", r.Key, r.Value))));
sb.Append("]");
Daniel
  • 920
  • 7
  • 19
4

I use following extension:

    public static String ToSeparatedString<T>(this IEnumerable<T> source, String separator)
    {
        return String.Join(separator, source.Select(e => e.ToString()).ToArray());
    }

In case when you need to get something formatted:

    public static String ToSeparatedString<T>(this IEnumerable<T> source, String separator, String format)
    {
        return String.Join(separator, source.Select(e => String.Format(format, e)).ToArray());
    }

Example of usage

    var myList = new List<String> {"a", "b", "c"};
    String result = myList.ToSeparatedString(",", "[{0}]");
    // result is "[a],[b],[c]" here
1
    sb.Append("\"DateSource\" : {");
    string separator = string.Empty;
    foreach (var row in DateSource)
    {
        sb.Append(separator);
        sb.Append("[");
        sb.Append(string.Format("\"RowKey\" : {0},", row.Key));
        sb.Append(string.Format("\"RowData\" : {0}", row.Value));
        sb.Append("]");
        separator = ",";
    }
    sb.Append("}");

Take into account that if row.Key and / or row.Value represent strings, you'll need to apply the format like this

        sb.Append(string.Format("\"RowKey\" : \"{0}\"", row.Key));
        sb.Append(string.Format("\"RowData\" : \"{0}\"", row.Value));

Note this \"{0}\"

Claudio Redi
  • 67,454
  • 15
  • 130
  • 155
0

I think I'll just use String.replace() to replace every

, ] --> ] 
, } --> }
Elad Benda
  • 35,076
  • 87
  • 265
  • 471