У меня есть небольшой метод проверки строки JSON с сервера:
public virtual bool DeSerializeResponse<ResponsedBodyType>(string RespBody)
{
var responsedBody = JsonConvert.DeserializeObject<ResponsedBodyType>(RespBody);
if (responsedBody == null)
return false;
else
return true;
}
Я называю этот метод примерно так:
bool Flag = DeSerializeResponse<SuccesType>("json_string");
Итак, если я получил правильный ответ от сервера - я успешно создаю объект SuccesType с непустыми свойствами. Но если сервер отправил мне другую строку JSON, я все равно получу, что responsedBody не является объектом NULL, хотя все его свойства пусты. Как я могу проверить правильность типа строки ответа?
UPD:
public class SuccesType
{
[JsonProperty]
public string access_token { get; set; }
[JsonProperty]
public string token_type { get; set; }
}
public class ServerError
{
[JsonProperty]
public string message { get; set; }
[JsonProperty]
public string reason { get; set; }
[JsonProperty]
public string details { get; set; }
}
Проверить тип? Пример прямо из Mickeysoft: int i = 0; System.Type type = i.GetType ();
Вы можете заменить if / else на return responsedBody == null
В основном просто получите имя типа того, что он сериализует, также вы можете использовать отражение для перечисления свойств.
@Trey проблема в том, что я не знаю, какой именно JSON будет отправлен с сервера. и если строка JSON соответствует ServerError (или другому), то responsesedBody должен быть нулевым.
Так это только два типа? SuccesType или ServerError?
Я бы просто использовал простое сравнение строк ... например, .Contains..или .Indexofany и т. д.
@Trey Сейчас уже 3 (+ "SessionEspired") и, возможно, еще больше в будущем. Я знаю - я могу проверить строку, но надеюсь, что есть способ получше.





public class SuccesType
{
[JsonProperty]
public string access_token { get; set; }
[JsonProperty]
public string token_type { get; set; }
}
public class ServerError
{
[JsonProperty]
public string message { get; set; }
[JsonProperty]
public string reason { get; set; }
[JsonProperty]
public string details { get; set; }
}
class Program
{
static void Main(string[] args)
{
string Jsonstr = @"{ ""accesstoken"":""test access token"", ""token_type"":""token test"" }";
bool testdeseralize = DeSerializeResponse<SuccesType>(Jsonstr);
}
private static bool DeSerializeResponse<T>(string RespBody)
{
JsonSerializerSettings testSettings = new JsonSerializerSettings();
testSettings.MissingMemberHandling = MissingMemberHandling.Error;
try
{
var responsedBody = JsonConvert.DeserializeObject<T>(RespBody, testSettings);
}
catch(JsonSerializationException ex)
{
return false;
}
return true;
}
}
Можете ли вы поделиться своим json?