C# 到 JSON 序列化使用 JSON.Net

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15843446/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 18:51:24  来源:igfitidea点击:

C# to JSON serialization using JSON.Net

jsonserializationjson.net

提问by Madhuri Mittal

I have a C# List which looks like this:

我有一个 C# 列表,如下所示:

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 ):

我使用下面的转换/序列化为 JSON ( Newtonsoft.JSON ):

var json = JsonConvert.SerializeObject(reqUsers);

With the above code I get a json string like this:

使用上面的代码,我得到一个像这样的 json 字符串:

[{ 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]" } ]

however here is what I need to get : since I am using handlebars templating -

然而,这是我需要得到的:因为我使用的是把手模板 -

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]" } ]

How can use the Serializer to name the JSON array as above ?

如何使用序列化程序命名 JSON 数组如上?

回答by devdigital

Use:

用:

var json = JsonConvert.SerializeObject(new { users = reqUsers });

回答by Hithesh

use:

用:

var json= new JavaScriptSerializer().Serialize(reqUsers);