我有一种从服务器检查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; }
}
答案 0 :(得分:3)
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;
}
}