使用 JSON.Net 的 C# 到 JSON 序列化 [英] C# to JSON serialization using JSON.Net
本文介绍了使用 JSON.Net 的 C# 到 JSON 序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
I have a C# List which looks like this:
var reqUsers = from user in users
select new
{
username = user.username,
firstName = user.firstName,
lastName = user.lastName,
email = user.email
};
I use the below to convert / serialize to JSON ( Newtonsoft.JSON ):
var json = JsonConvert.SerializeObject(reqUsers);
With the above code I get a json string like this:
[{ username: "alan", firstName: "Alan", lastName: "Johnson", email: "alan@test.com" },
{ username: "allison", firstName: "Allison", lastName: "House", email: "al@test.com" },
{ username: "ryan", firstName: "Ryan", lastName: "Carson", email: "ryan@test.com" } ]
however here is what I need to get : since I am using handlebars templating -
var testdata = {
users: [
{ username: "alan", firstName: "Alan", lastName: "Johnson", email: "alan@test.com" },
{ username: "allison", firstName: "Allison", lastName: "House", email: "al@test.com" },
{ username: "ryan", firstName: "Ryan", lastName: "Carson", email: "ryan@test.com" } ]
How can use the Serializer to name the JSON array as above ?
解决方案
Use:
var json = JsonConvert.SerializeObject(new { users = reqUsers });
这篇关于使用 JSON.Net 的 C# 到 JSON 序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文