0

My question is similar to this question - JSON.NET deserialize a specific property . Except I want to deserialize the whole object but also use a custom method to deserialize a specific property in the class. The way I'm doing it right now is deserializing the whole object, and then calling a custom method again to deserialize a specific property in that object. This works, but I don't think it is very efficient.

 public class Foo
 {
     public int id { get; set; }
     public object item { get; set; }
 }

 object obj = JsonConvert.DeserializeObject(json, typeof(Foo));

 //This method is from the previously asked question and it works.
 object item = GetFirstInstance<GenericFoo<object>>("item", json); 

 Foo castedFoo= (Foo)obj;
 castedFoo.item = item;

How can I update this code to make it more efficient? Something like ignore item property when the first time the object is getting deserialized?

user3587180
  • 1,317
  • 11
  • 23
  • Have you tried using a [custom `JsonConverter`](http://www.newtonsoft.com/json/help/html/CustomJsonConverter.htm) as shown [here](https://stackoverflow.com/q/8030538/3744182) or [here](https://stackoverflow.com/q/8030538/3744182)? – dbc Jun 17 '17 at 18:43
  • @dbc Thanks for the links. I don't think I'm following that example. How do I first deserailzie the whole object (but ignore item property) and then deserialize the item property? – user3587180 Jun 17 '17 at 19:16
  • This sounds like an [xy problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). You want to deserialize it *correctly*. Why do you need to deserialize it in two passes if it can be deserialized correctly in one pass? – dbc Jun 17 '17 at 19:18
  • @dbc It's a little hard to explain without showing you the whole code but I'll try. The value of the item property is an f# discriminated union tuple. The default deserialize implementation is giving me trouble, so I need to specify the type explicitly for just that one "item" property. Hope that helps. – user3587180 Jun 17 '17 at 19:21
  • @dbc And I don't want to deserailize in two steps. The only reason I'm doing it is because of the f# discriminated union type. Newtonsoft is not inferring the right type. – user3587180 Jun 17 '17 at 19:24
  • 1
    What does the JSON look like? – Brian Rogers Jun 18 '17 at 03:32

0 Answers0