使用JSON.Net从C#到JSON序列化 [英] C# to JSON serialization using JSON.Net
本文介绍了使用JSON.Net从C#到JSON序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个C#列表,看起来像这样:
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
};
我使用以下代码将JSON转换/序列化为(Newtonsoft.JSON):
I use the below to convert / serialize to JSON ( Newtonsoft.JSON ):
var json = JsonConvert.SerializeObject(reqUsers);
使用上面的代码,我得到一个像这样的json字符串:
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" } ]
如何使用序列化器如上所述命名JSON数组?
How can use the Serializer to name the JSON array as above ?
推荐答案
使用:
var json = JsonConvert.SerializeObject(new { users = reqUsers });
这篇关于使用JSON.Net从C#到JSON序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文