Jason Webber
Jason Webber

Reputation: 323

Newtonsoft Deserialize to Object Store Underlying JSON as property

I am using Newtonsoft to deserialize JSON from a REST call to a C# object. The object is a list of Person. The Person has a lot of properties but right now I am only storing some of them. I want to have a string property on the Person that contains the JSON that makes up the whole person. Is there a way to do this? I am writing it back to a SQL database for now and I don't need the values but want to have it for future use if needed.

Object class

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; }
}

My existing call to deserialize:

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

Upvotes: 0

Views: 1695

Answers (2)

gnud
gnud

Reputation: 78528

I think you mean that you want to store all attributes from the JSON into your c# object - so that you can access them later if you need to.

To do this, you use the [JsonExtensionData] annotation.

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;}
}

You can see a full example at https://dotnetfiddle.net/N5SuCY.

To store these properties in a database, you can combine this with a calculated string property:

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

Upvotes: 4

Shaked Dahan
Shaked Dahan

Reputation: 402

Add JsonIgnore attribute to your JSON property like this:

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

You can use do this after you have deserialized the object

JObject workerResult = JObject.Parse(json);

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

After that, iterate all the workers in the result object you obtained earlier and set the JSON property to the equivalent worker object

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

Upvotes: 1

Related Questions