c# - 有没有办法为每个对象编写自定义 JsonConverter

标签 c# json json.net

我有一个像这样的 Json 对象:

{"company": "My Company",
"companyStart" : "2015/01/01",
"employee" : 
    { "name" : "john doe",
      "startDate" : 1420434000000 } }

我的 json 对象是这样的:

public class Company {
    public string company;
    public DateTime companyStart;
    public Employee employee;
}

public class Employee {
    public string name;
    public DateTime startDate;
 }

我的原始代码是这样反序列化的

JsonConvert.DeserializeObject<Company>(jsonString);

这段代码可以毫无问题地转换 Company.companyStart,但是当它到达 Employee.startDate 时,它​​不知道如何处理 Long。

This帖子向我展示了如何创建自定义 JsonConverter 以将 long 转换为 DateTime,但正如您在我的案例中看到的那样,这会给我带来将 Company.companyStart 转换为 DateTime 的麻烦。

所以...我正在考虑做这样的事情:

public class Company : JsonBase {
    ...
}

public class Employee : JsonBase {
    ...
    Employee() { Converter = new CustomDateConverter(); }
}

public class JsonBase {
    private JsonConverter converter;
    [JsonIgnore]
    public JsonConverter Converter => converter ?? (converter = new StandardConverter());
}

JsonBase 将包含标准转换器或

在我的代码中,我会这样转换:

public T CreateJsonObject<T>() where T : JsonBase {
    JsonBase json = (T) Activator.CreateInstance(typeof (T));
    JsonConvert.DeserializeObject<T>(jsonString, json.Converter);
}

问题是这不太有效,因为此方法将简单地使用最顶层的 Converter 来转换所有内容,而不是对每个对象使用转换器。

有没有办法为每个对象使用转换器?或者也许有更好的方法来做到这一点。

最佳答案

如何调整您编写的自定义转换器以理解这两种格式:

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
    if (reader.ValueType == typeof(string))
    {
        return DateTime.Parse((string)reader.Value);
    }
    else if (reader.ValueType == typeof(long))
    {
        return new DateTime(1970, 1, 1).AddMilliseconds((long)reader.Value);
    }
    throw new NotSupportedException();
}

或者,您可以通过使用 JsonConverter 属性装饰它,仅将转换器应用于模型的特定属性:

public class Employee
{
    public string name;

    [JsonConverter(typeof(MyConverter))]
    public DateTime startDate;
}

这样您就不需要在全局范围内注册转换器,它也不会与其他标准日期格式混淆。

关于c# - 有没有办法为每个对象编写自定义 JsonConverter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34419289/

相关文章:

c# - 数据网格列标题按钮

python - python转换JSON请求时出现 "httpMessageNotReadableException"的错误消息

java - 使用 Gson 反序列化 JSON

c# - 将带有数组的 json 结构展平为多个没有数组的平面对象

c# - MVC 网站不接收来自客户端的字符串

C# 和 LINQ;将文件分组为 5MB 组

C# 不通过返回类型推断重载方法

twitter - Newtonsoft.Json 依赖问题

c# - xUnit.net 与 Ninject

java - 如何在 restFul 服务 URL 末尾添加参数?