Reputation: 1951
After populating an EF Object (users
for instance) with data and return it from WebAPI, i get it in json format as follows:
[
{"username":"lakshman553","email":"[email protected]","phone":1234567},
{"username":"lakshman323","email":"[email protected]","phone":"122267"},
]
Since i use the webapi completely for internal purposes, i would rather like the data as follows:
[
["lakshman553","[email protected]",1234567],
["lakshman323","[email protected]",1222267]
]
i can decrease the payload drastically by doing this way when the data is high, which typically is the case.
How to achieve this in C#. Iterating through the users
object and assigning it to a sized array of row and column count is one approach i know, but is there a straight method for doing this?
thanks.
Upvotes: 1
Views: 1009
Reputation: 6100
Using Json.NET:
var users = new[]
{
new { username = "lakshman553", email = "[email protected]", phone = "1234567" },
new { username = "lakshman323", email = "[email protected]", phone = "122267" }
};
JsonConvert.SerializeObject(JArray.FromObject(users).Select(_ => _.Values()));
Output:
[["lakshman553","[email protected]","1234567"],["lakshman323","[email protected]","122267"]]
Upvotes: 0
Reputation: 64943
You could implement this transformation using LINQ extension methods as follows:
// Project each list item into an array of item property values
var array4all = list.Select
(
item => item.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public)
.Select(property => property.GetValue(item))
.ToArray()
).ToArray();
BTW, IMHO I'm concerned about this sentence:
Since i use the webapi completely for internal purposes [...]
I believe you're trying to simplify the problem creating a new problem. In terms of coding, readability and maintainaibility I find that you're making things tougher.
Maybe something like obfuscating property names to a
, b
, c
.... and you might use AutoMapper to map a dynamic
DTO to your actual model/DTO with full property names. Something like:
{ "a": "hello world", "b": 20 } => { "text": "hello world", "number": 20 }
Or you can take a look at MsgPack, BSON...
Upvotes: 2
Reputation: 388313
If you gzip your server’s response (which you should), then those repeated property names don’t really matter much. On the other hand, having the properties as properties makes handling the data a lot easier for both the provider and the consumer.
You say you use it only for internal purposes, but you’d still need to build a custom parsing mechanism for this when you consume that data. And to do that, you need to have a consistent way of doing so, so you need additional contracts that define e.g. the order of the properties, and—when parsing into C#—also its types etc.
That’s a lot overhead just to reduce the bandwidth, which as I said above doesn’t really matter much once you gzip the data.
Upvotes: 1