I have a question regarding the newly released .NET Core 3.0 and its new System.Text.Json
, I would like to ask if the new JsonDocument
could be used similarly to ContractResolver
class in Newtonsoft JSON.NET.
What I need is quite straightforward, assume one class with two properties
public string Name {get; set;} public string Street {get; set;}
and I need to deserialize two different JSONs into this class.
JSON 1:
{"person_A":{"full-name":"Micheal","address-street":"1st avenue","address-city":"New York"}, "person_B":{"full-name":"John","address-street":"Green street","address-city":"London"}}
JSON 2:
{"man_A":{"fullname":"Bush","street":"1st avenue","city":"Washington","state":"US"}, "woman_B":{"fullname":"McCarter","street":"Green street","city":"London","state":"GB"}}
I need to deserialize property full-name
, fullname
as Name
and address-street
,street
as Street
. The other JSON fields are not needed.
To deserialize multiple JSON with different property names I am using a ContractResolver
in JSON.NET, which works quite well.
The reason why I am looking into the JsonDocument
is that I am deserializing just few JSON properties and with current approach I have to cache entire JSON. If I uderstood correctly, the JsonDocument
should allow me to access just the properties I need.
Thanks!
EDIT
To clarify a bit what I am trying to ask here - the idea is to get info about the Json object but not to load it entirely since it is not needed, that's why I would like to use the new JsonDocument, select just the things that I need and load those. Since the Json property names are different than my class properties and I have multiple Json trying to deserialize into the same class, I need something like IContractResolver to match the class properties with the names in Json.
I was able to make something like this working, but I admit it is not very pretty.
private readonly Dictionary propertyMappings = new Dictionary();
private void AddMap<U>(Expression<Func<Instrument,U>> expression, string jsonPropertyName) { var memberExpression = (MemberExpression)expression.Body; propertyMappings.Add(memberExpression.Member.Name, jsonPropertyName); } public override async Task<List<Person>> GetPeopleAsync(HttpRequestMessage request) { AddMap(x => x.Name, "full-name"); AddMap(x => x.Street, "address-street"); var result = new List<Person>(); var response = await SendAsync(request, HttpCompletionOption.ResponseHeadersRead); var stream = await response.Content.ReadAsStreamAsync(); var document = await JsonDocument.ParseAsync(stream); document.RootElement.GetProperty("people").EnumerateObject() .ToList() .ForEach(x => { var person= new Person(); foreach (var p in propertyMappings) { x.Value.TryGetProperty(p.Value, out var prop); var v = person.GetType().GetProperty(p.Key); v.SetValue(person,Convert.ChangeType(prop.ToString(),v.PropertyType)); } result.Add(person); }); return result; }</code>