【问题标题】:How to serialize object without curly braces in .Net Core如何在.Net Core中序列化没有大括号的对象
【发布时间】:2023-02-03 19:07:38
【问题描述】:

我正在使用 Newton Json 作为序列化对象。我想序列化一个具有两个属性的对象,一个是普通字符串,第二个属性是某些项目的字典。

我期待这样的结果:

"Company": {
            "Id": "1393",
            "emp1": {
                "email": "test1@example.com",
                "firstName": "test1",
                "lastName": "test1",
                "title": "Mr"
            },
            "emp2": {
                "email": "test2@example.com",
                "firstName": "test2",
                "lastName": "test2",
                "title": "Ms"
            }
        }

但我得到如下输出:

"Company": {
            "Id": "1393",
            "employees": {
                "emp1": {
                    "email": "test1@example.com",
                    "firstName": "test1",
                    "lastName": "test1",
                    "title": "Mr"
                 },
                 "emp2": {
                    "email": "test2@example.com",
                    "firstName": "test2",
                    "lastName": "test2",
                    "title": "Ms"
              }
            }
        }

这是我的代码:

public string GetCompany(Dictionary<string, Employee> employees)
        {
            var company = JsonConvert.SerializeObject(new
            {
                Id = "1393",
                employees
            });

            return company;
        }

【问题讨论】:

    标签: c# json .net .net-core


    【解决方案1】:

    通过创建匿名对象,您添加了另一个名为employees 的属性。

    为什么不直接将 Id 添加到字典中呢?

    例如

    var company = JsonConvert.SerializeObject(new Dictionary<string, object>(employees)
    {
        ["Id"] = "1393"
    });
    

    这会复制 employees 并在序列化之前添加一个新密钥 "Id"

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-26
      • 2014-02-09
      • 1970-01-01
      • 2017-05-26
      • 2021-11-16
      • 2011-02-10
      • 1970-01-01
      • 2020-01-26
      相关资源
      最近更新 更多