I have the following JSON
text:
{ "PropOne": { "Text": "Data" } "PropTwo": "Data2" }
I want to deserialize PropOne
into type PropOneClass
without the overhead of deserializing any other properties on the object. Can this be done using JSON.NET?
The JSON isn't too large, so I'll take Matt Johnson's suggestion and deserialize the whole thing. Thanks to jcwrequests answer, I was able to use this method:
var jObject = JObject.Parse(json); var jToken = jObject.GetValue("PropTwo"); PropTwoClass value = jToken.ToObject(typeof(PropTwoClass));
public T GetFirstInstance<T>(string propertyName, string json) { using (var stringReader = new StringReader(json)) using (var jsonReader = new JsonTextReader(stringReader)) { while (jsonReader.Read()) { if (jsonReader.TokenType == JsonToken.PropertyName && (string)jsonReader.Value == propertyName) { jsonReader.Read(); var serializer = new JsonSerializer(); return serializer.Deserialize<T>(jsonReader); } } return default(T); } } public class MyType { public string Text { get; set; } } public void Test() { string json = "{ \"PropOne\": { \"Text\": \"Data\" }, \"PropTwo\": \"Data2\" }"; MyType myType = GetFirstInstance<MyType>("PropOne", json); Debug.WriteLine(myType.Text); // "Data" }
This approach avoids having to deserialize the entire object. But note that this will only improve performance if the json is significantly large, and the property you are deserializing is relatively early in the data. Otherwise, you should just deserialize the whole thing and pull out the parts you want, like jcwrequests answer shows.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With