Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON.NET deserialize a specific property

Tags:

c#

json.net

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?

like image 924
Omar Avatar asked Oct 17 '13 22:10

Omar


2 Answers

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)); 
like image 67
Omar Avatar answered Sep 28 '22 08:09

Omar


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.

like image 34
Matt Johnson-Pint Avatar answered Sep 28 '22 08:09

Matt Johnson-Pint