tags:

views:

145

answers:

4

Hi folks,

i've got an IList<Foo> and I'm trying to serialize it as Json without the field names included in the result. As such, i'm trying to create an anonymous object, which i pass to the Json serialization method.

Foo is defined as (pseudo code):-

public class Foo
{
    public int X;
    public int Y;
}

When i return this as Json ...

return Json(foos);

the result is like

... [{"X":1,"Y":2},{"X":3,"Y":4}...]

I don't want the X and Y to be there. So i'm after..

... [{1,2},{3,4}...]

So i was trying to do the following (which doesn't work)

(from p in foos
 select new p.X + "," + p.Y).ToArray()

or

(from p in foos
 select new string(p.X+ "," + p.Y)).ToArray()

but to no avail (doesn't compile).

Can anyone help, please?

+5  A: 
foos.Select(p=>p.X + "," + p.Y)

Or if you perfer Linq Syntax:

(from p in foos
 select p.X + "," + p.Y).ToArray()
Kai Wang
A: 

Why not just create the JSON string yourself, so you have complete control over how it is set up rather than using the Serialization method.

James Black
+1  A: 

JSON is a member serializer, and uses the names. If you don't want names, don't use JSON. Perhaps just StringBuilder, then?

StringBuilder sb = new StringBuilder("[");
foreach(var foo in items) {
  sb.Append('{').Append(foo.X).Append(',').Append(foo.Y).Append("},");
}
sb[sb.Length - 1] = ']';
string s = sb.ToString();
Marc Gravell
can this be done as LINQ?
Pure.Krome
LINQ is a tool. Just a tool. It isn't the answer to every problem.
Marc Gravell
true .. but i find i make my code a lot more readable with some succinct linq queries.
Pure.Krome
+7  A: 
(from p in foos
 select String.Format("{{{0}, {1}}}", p.X, p.Y)).ToArray()
Thomas Levesque
God, Linq is beautifully elegant and powerful.
hypoxide