1

I have an API that returns a JSON array with 6000 objects. Each object has around 40 properties, but I only need to use around 20. How do ignore certain properties? Here is my current code:

string json = await client.GetStringAsync(string.Format(url));
List<ListModelClass> ListOfStuff = JsonConvert.DeserializeObject<List<ListModelClass>>(JArray.Parse(json).ToString());

public class ListModelClass {
    public string firstProperty { get; set; }
    public string secondProperty { get; set; }
    public string thirdProperty { get; set; }
    ... about 40 more 
}
james
  • 171
  • 1
  • 1
  • 10
  • 3
    Newtonsoft.Json will try and match properties based on name. If the property doesn't exist in your class, it won't be added. – Zac Faragher Mar 29 '17 at 22:18
  • will the `ScriptIgnore` attribute over the property work? – toddmo Mar 29 '17 at 22:22
  • @ZacFaragher I thought that, but I wondered if it still did the comparison. I'm trying to reduce the time it takes for the whole operation. – james Mar 29 '17 at 22:24
  • If that's the case then your source JSON response itself needs to be modified. – tRuEsAtM Mar 29 '17 at 22:25
  • @ZacFaragher That would be the best case, but unfortunately that is not possible. – james Mar 29 '17 at 22:32
  • Simply not including the unwanted properties in the c# model is almost certainly the fastest way to ignore them given that the JSON cannot be modified. Though see Erik Lippert's [discussion](https://ericlippert.com/2012/12/17/performance-rant/) on this. – dbc Mar 29 '17 at 22:36
  • @dbc Thanks I'll go with that then :) – james Mar 29 '17 at 22:37
  • Possible duplicate of [How to exclude property from Json Serialization](http://stackoverflow.com/questions/10169648/how-to-exclude-property-from-json-serialization) – user1378730 Mar 29 '17 at 22:43
  • @james What sort of benchmarking have you already done? Do you know that the time taken is unacceptably long and needs to be reduced or are you doing Premature Optimization? I know it's something that I struggle with too... – Zac Faragher Mar 30 '17 at 00:02

1 Answers1

0

Properties in the JSON object match if and only if there is a property in the model class with the same name or you can use [JsonProperty(PropertyName = "your_property_name")]

So you can only include the properties which you want to use in your model class.

tRuEsAtM
  • 3,517
  • 6
  • 43
  • 83