J'ai une liste C # qui ressemble à ceci:
var reqUsers = from user in users
select new
{
username = user.username,
firstName = user.firstName,
lastName = user.lastName,
email = user.email
};
J'utilise ce qui suit pour convertir/sérialiser en JSON (Newtonsoft.JSON):
var json = JsonConvert.SerializeObject(reqUsers);
Avec le code ci-dessus, j'obtiens une chaîne json comme ceci:
[{ username: "alan", firstName: "Alan", lastName: "Johnson", email: "[email protected]" },
{ username: "allison", firstName: "Allison", lastName: "House", email: "[email protected]" },
{ username: "ryan", firstName: "Ryan", lastName: "Carson", email: "[email protected]" } ]
mais voici ce que je dois obtenir: puisque j'utilise des modèles de guidon -
var testdata = {
users: [
{ username: "alan", firstName: "Alan", lastName: "Johnson", email: "[email protected]" },
{ username: "allison", firstName: "Allison", lastName: "House", email: "[email protected]" },
{ username: "ryan", firstName: "Ryan", lastName: "Carson", email: "[email protected]" } ]
Comment utiliser le sérialiseur pour nommer le tableau JSON comme ci-dessus?
Utilisation:
var json = JsonConvert.SerializeObject(new { users = reqUsers });
utilisation:
var json= new JavaScriptSerializer().Serialize(reqUsers);