【问题标题】:Newtonsoft Deserialize to Object Store Underlying JSON as propertyNewtonsoft 反序列化到对象存储底层 JSON 作为属性
【发布时间】:2018-09-18 06:26:59
【问题描述】:

我正在使用 Newtonsoft 将 JSON 从 REST 调用反序列化为 C# 对象。该对象是一个人员列表。 Person 有很多属性,但现在我只存储其中的一些。我想在 Person 上有一个字符串属性,其中包含构成整个人的 JSON。有没有办法做到这一点?我现在正在将其写回 SQL 数据库,我不需要这些值,但希望在需要时将其保留以备将来使用。

对象类

public class Worker
{
    public string associateOID { get; set; }
    public WorkerID workerID { get; set; }
    public Person person { get; set; }
    public WorkerDates workerDates { get; set; }
    public WorkerStatus workerStatus { get; set; }
    public List<WorkAssignment> workAssignments { get; set; }
    public CustomFieldGroup customFieldGroup { get; set; }
    public BusinessCommunication businessCommunication { get; set; }
    public string JSON { get; set; }
}

public class Meta
{
    public int totalNumber { get; set; }
}

public class WorkerResult
{
    public List<Worker> workers { get; set; }
    public Meta meta { get; set; }
}

我现有的反序列化调用:

WorkerResult result = JsonConvert.DeserializeObject<WorkerResult>(json);

【问题讨论】:

标签: c# json json.net


【解决方案1】:

我认为您的意思是要将 JSON 中的所有属性存储到您的 c# 对象中 - 以便您以后可以在需要时访问它们。

为此,您可以使用[JsonExtensionData] 注释。

public class Worker
{
    public string associateOID { get; set; }
    // Any other attributes that you want to use as .NET types go here

    // all attributes that don't have a property will be put into this dictionary
    // either as primitive types, or as objects of type Newtonsoft.Json.Linq.JObject
    // supports nested objects of any Json structure, and will serialize correctly.
    [JsonExtensionData]
    public Dictionary<string,object> ExtraAttributes {get;set;}
}

您可以在https://dotnetfiddle.net/N5SuCY 上查看完整示例。

要将这些属性存储在数据库中,您可以将其与计算的字符串属性相结合:

[JsonIgnore]
public string SerializedExtraAttributes => JsonConvert.SerializeObject(ExtraAttributes);

【讨论】:

    【解决方案2】:

    像这样将 JsonIgnore 属性添加到您的 JSON 属性中:

    [JsonIgnore()]
    public string JSON { get; set; }
    

    您可以在反序列化对象后使用它

    JObject workerResult = JObject.Parse(json);
    
    // this should contain a list of all the workers
    IList<JToken> workers = workerResult["workers"].Children().ToList();
    

    之后,迭代你之前获得的result对象中的所有worker,并将JSON属性设置为等效的worker对象

    for (int i = 0; i < result.workers.Count; i++)
        result.workers[i].JSON = workers[i].ToString();
    

    【讨论】:

    • JSON 位于列表中向下 2 层的对象中。
    • @JasonWebber 我已更新我的答案以匹配您的对象
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多