【问题标题】:How to deserialize JSON object using constructor into itself in C#? [duplicate]如何在 C# 中使用构造函数将 JSON 对象反序列化为自身? [复制]
【发布时间】:2019-01-06 12:17:35
【问题描述】:

我想创建一个新对象,并在创建对象期间进行 RPC 调用以获取它的属性,然后返回填充有属性的对象。看这个例子:

using Newtonsoft.Json;

class Person
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public Person(int Id)
    {
        // here would be an RPC call to get the FirstName,LastName. result is JSON
        string result = "{\"Id\": 1, \"FirstName\": \"Bob\", \"LastName\": \"Jones\"}";
        this = JsonConvert.DeserializeObject<Person>(result);

    }
}
class Program
{
    static void Main(string[] args)
    {
        var p = new Person(1);
        // p.FirstName should be Bob
    }
}

如果没有 StackOverflow 异常,我不知道如何在构造函数中执行此操作。

【问题讨论】:

  • 您收到 StackOverflow 异常,因为 DeserializeObject 创建了一个新对象,即它调用了构造函数。并且您的构造函数调用 DeserializeObject,即您创建了一个无循环的循环。
  • var p = Person.StaticFactoryMethod(1); - 尽管模型或 DTO 不应实现自己的持久性。

标签: c# json deserialization json-deserialization


【解决方案1】:

要考虑的一个选项是在Person 中使用静态方法:

public static Person GetPerson(int Id)
{
    // here would be an RPC call to get the FirstName,LastName. result is JSON
    string result = "{\"Id\": 1, \"FirstName\": \"Bob\", \"LastName\": \"Jones\"}";
    return JsonConvert.DeserializeObject<Person>(result);

}

这避免了原始代码的递归性质。

另一种选择是将class 更改为structstructs 允许您分配给this(与classes 不同)。他们有一个默认的构造函数(与你的带参数的构造函数分开),因此没有递归行为。

【讨论】:

    猜你喜欢
    • 2016-09-25
    • 1970-01-01
    • 2012-12-15
    • 1970-01-01
    • 2011-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-19
    相关资源
    最近更新 更多