JSON.NET deserialize a specific property

前端 未结 6 2212
时光说笑
时光说笑 2020-11-30 07:36

I have the following JSON text:

{
    \"PropOne\": {
        \"Text\": \"Data\"
    }
    \"PropTwo\": \"Data2\"
}    

I want

6条回答
  •  情书的邮戳
    2020-11-30 07:54

    public T GetFirstInstance(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(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("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.

提交回复
热议问题