Disable derived classes using Json.net without using JObject

I have a large json dataset that I need to deserialize. I am using Json.net JsonTextReader to read data.

My problem is that I need to deserialize some derived classes, so I need to be able to "look ahead" for a specific property that defines my data type. In the example below, the "type" parameter is used to determine the type of object to deserialize.

 { type: "groupData", groupParam: "groupValue1", nestedObject: { type: "groupData", groupParam: "groupValue2", nestedObject: { type: "bigData", arrayData: [ ... ] } } 

My derived objects can be very nested and very deep. Loading the entire data set into memory is undesirable since it will require a lot of memory. When I move to the "bigData" object, I will process the data (for example, the array in the example above), but it will not be stored in memory (it is too large).

All the solutions to my problem that I have seen so far have used JObject to deserialize partial objects. I want to avoid using JObject because it will deserialize each object in the hierarchy again.

How can I solve the problem of deserialization?

Is there a way to search by the "type" parameter, and then return to the beginning of the object {symbol to start processing?

+8
json c #
source share
1 answer

I don’t know how to start loading the object to specify lookahead (at least not in Json.NET), but you can use other attribute-based configuration items at your disposal to ignore unwanted properties

 public class GroupData { [JsonIgnore] public string groupParam { get; set; } [JsonIgnore] public GroupData nestedObject { get; set; } public string[] arrayData { get; set; } } 

Alternatively, you can give custom creation converters :

For example..

 public class GroupData { [JsonIgnore] public string groupParam { get; set; } [JsonIgnore] public GroupData nestedObject { get; set; } } public class BigData : GroupData { public string[] arrayData { get; set; } } public class ObjectConverter<T> : CustomCreationConverter<T> { public ObjectConverter() { } public override bool CanConvert(Type objectType) { return objectType.Name == "BigData"; } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { // Some additional checks/work? serializer.Populate(reader, target); } } 
+1
source share

All Articles