I use RestSharp to send a request to the Yandex API, but for some reason the result variable is not populated.

JSON is clearly visible in the response variable.

public Result GetLangByString(string str) { var request = new RestRequest("/api/v1.5/tr.json/detect", Method.POST); request.Credentials = CredentialCache.DefaultCredentials; request.AddParameter("key", _key); request.AddParameter("text", str); IRestResponse response = _restClient.Execute(request); RestSharp.Deserializers.JsonDeserializer deserializer = new RestSharp.Deserializers.JsonDeserializer(); var result = deserializer.Deserialize<Result>(response); return result; } public class Result { public int code; public string lang; } 

If the fields are replaced with properties, then everything works. Are these any particulars or is it accepted?

  • one
    Well, in WPF, for example, fields are also ignored. What sticks out outside should be a property in an amicable way. (And as is customary in your particular library, I do not know.) - VladD
  • Strange, like XML works fine without properties. Probably a feature. - iluxa1810

2 answers 2

Of course, fields in this case will be ignored when the result is deserialized. It depends on the specific implementation of the deserialization method. In the RestSharp library, this method looks like this:

 private void Map(object target, IDictionary<string, object> data) { var objType = target.GetType(); var props = objType.GetProperties().Where(p => p.CanWrite).ToList(); foreach (var prop in props) { var type = prop.PropertyType; var name = prop.Name; var actualName = name.GetNameVariants(Culture).FirstOrDefault(n => data.ContainsKey(n)); var value = actualName != null ? data[actualName] : null; if (value == null) continue; // check for nullable and extract underlying type if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) { type = type.GetGenericArguments()[0]; } prop.SetValue(target, ConvertValue(type, value), null); } } 

As can be seen from the above code, the method gets through reflection the necessary properties of the constructed target object of type T (in your case it will be the Result class) and fill them with the necessary values ​​from the dictionary.

    That's right! There are no glitches! You can only change properties! And the fields are just variables that are not associated as objects of a class and do not have such an important property as "Data BINDING". Here you have nothing and does not work with the "FIELDS" ...

    • It seems, for XML and fields it is enough if I am not mistaken. Strange that JSON doesn't like it. - iluxa1810