如何在 C# 中编写自定义 JSon 序列化程序

how to write Custom JSon serializer in C#

我正在使用 Newtonsoft json 序列化程序将 json 字符串转换为对象。我有 json 结构如下 -

{
    "EmployeeRecords": {
        "12": {
            "title": "Mr",
            "Name": "John"
        },
        "35":{
            "title": "Mr",
            "Name": "Json"
        }
    }
}

我希望这个 Json 序列化到下面 class -

public class Employee
{
    public string EmployeeNumber { get; set; }
    public string title { get; set; }
    public string Name { get; set; }
}

public class EmployeeRecords
{
    public List<Employee> Employees { get; set; }
}

此处Employeenumber为12和35。

请指导我如何编写自定义序列化程序,它将从父节点读取员工编号并将其包含在子节点的员工编号中 属性。

您可以反序列化到字典中,然后在循环中分配 EmployeeNumbers。

public class DataModel
{
    public Dictionary<string, Employee> EmployeeRecords { get; set; }
}

反序列化后赋值:

var records = JsonConvert.DeserializeObject<DataModel>(json);

foreach (var item in records.EmployeeRecords)
{
    item.Value.EmployeeNumber = item.Key;
}

您可以使用 LINQ to JSON(JObject 和朋友)轻松地做到这一点。这是一个简短但完整的示例:

using System;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;

public class Employee
{
    public string EmployeeNumber { get; set; }
    public string title { get; set; }
    public string Name { get; set; }

    public JProperty ToJProperty()
    {
        return new JProperty(EmployeeNumber,
            new JObject {
                { "title", title },
                { "Name", Name }
            });
    }
}

public class EmployeeRecords
{
    public List<Employee> Employees { get; set; }

    public JObject ToJObject()
    {
        var obj = new JObject();
        foreach (var employee in Employees)
        {
            obj.Add(employee.ToJProperty());
        }
        return new JObject {
            new JProperty("EmployeeRecords", obj)
        };
    }
}

class Test
{
    static void Main()
    {
        var records = new EmployeeRecords {
            Employees = new List<Employee> {
                new Employee {
                    EmployeeNumber = "12",
                    title = "Mr",
                    Name = "John"
                },
                new Employee {
                    EmployeeNumber = "35",
                    title = "Mr",
                    Name = "Json"
                },
            }
        };
        Console.WriteLine(records.ToJObject());
    }    
}

它可能不是最简单的代码(如果您乐于更改结构,Ufuk 的方法很棒),但它显示了所有内容的可定制性。