繁体   English   中英

Newtonsoft反序列化到对象存储底层JSON作为属性

[英]Newtonsoft Deserialize to Object Store Underlying JSON as property

我正在使用Newtonsoft从REST调用到C#对象反序列化JSON。 该对象是“个人”列表。 该人具有很多属性,但是现在我只存储其中一些。 我想在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);

我认为您的意思是要将所有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);

将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对象中的所有工作程序,并将JSON属性设置为等效的工作程序对象

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM