2
byte[] val = { 3, 4, 5 };

Dictionary<String, Object> dict = new Dictionary<String, Object>();
dict.Add("val", val);
//...

string request_json = new JavaScriptSerializer().Serialize(dict);
Console.Out.WriteLine(request_json);

This produces

{"val":[3,4,5]}

What's the best way to convert val such that the above produces the following (or equivalent) instead:

{"val":"\u0003\u0004\u0005"}

(This is passed to a web service which expects a string of arbitrary bytes rather than an array of arbitrary bytes.)


In case it helps, I would have used the following in Perl:

pack "C*", @bytes

A more descriptive Perl solution would be:

join "", map { chr($_) } @bytes
ikegami
  • 367,544
  • 15
  • 269
  • 518

2 Answers2

2

This should do the trick:

dict.Add("val", String.Join("", val.Select(_ => (char)_)));

or as suggested by Michael:

dict.Add("val", String.Concat(val.Select(_ => (char)_)));
rbm
  • 3,243
  • 2
  • 17
  • 28
1

One possible solution:

StringBuilder sb = new StringBuilder(val.Length);
foreach (byte b in val) {
    sb.Append((char)b);
}

dict.Add("val", sb.ToString());

Note: Convert.ToChar(b) could be used instead of (char)b.

ikegami
  • 367,544
  • 15
  • 269
  • 518