我有一个使用 API 方法的服务,它返回一个 json 字符串。我在下面有一个基本响应对象:
public class BaseResponse
{
public bool HasError { get; set; }
public string Message { get; set; }
}
和泛型类型解析器
Task<R> ParseResponse<R>(HttpResponseMessage response) where R : BaseResponse, new()
返回:
return JsonConvert.DeserializeObject<R>(responseText);
请注意,我无法控制 API 的响应。所以我得到这个响应,一个对象数组。
[{"created":"0001-01-01T00:00:00","updated":null,"name":"Test 1","decscription":null,"id":1},{"created":"0001-01-01T00:00:00","updated":null,"name":"Test 2","decscription":null,"id":2},{"created":"0001-01-01T00:00:00","updated":null,"name":"Test 3","decscription":null,"id":3},{"created":"0001-01-01T00:00:00","updated":null,"name":"Test 4","decscription":null,"id":4}]
问题是我想将其解析为此类:
public class TestResponse : BaseResponse
{
public Test[] Tests { get; set; }
}
当服务器上发生错误或 api 返回错误请求等时,HasError
和Message
将具有一个值。
任何信息将不胜感激。谢谢。
从您的评论来看,听起来好像成功的响应将显示为 JSON 数组,但如果发生错误,则将返回一个带有错误标志和消息的 JSON 对象。 为了解析这两种可能的响应,您可以创建一个自定义JsonConverter
来检查收到的 JSON 是数组还是对象,并相应地继续:
public class TestResponseConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(TestResponse);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
return null;
else if (reader.TokenType == JsonToken.StartArray)
{
// A valid response. Populare the Tests array.
var tests = serializer.Deserialize<Test[]>(reader);
return new TestResponse { Tests = tests };
}
else if (reader.TokenType == JsonToken.StartObject)
{
// An error response. Populate HasError and Message
var response = new TestResponse();
serializer.Populate(reader, response);
return response;
}
else
{
throw new JsonSerializationException("Unexpected reader.TokenType: " + reader.TokenType);
}
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var test = (TestResponse)value;
if (test.HasError && test.Tests != null && test.Tests.Length > 0)
{
serializer.Serialize(writer, new { HasError = test.HasError, Message = test.Message, Tests = test.Tests });
}
else if (test.HasError || test.Tests == null)
{
serializer.Serialize(writer, new { HasError = test.HasError, Message = test.Message });
}
else
{
serializer.Serialize(writer, test.Tests);
}
}
}
然后使用如下所示JsonConverterAttribute
将其应用于类:
[JsonConverter(typeof(TestResponseConverter))]
public class TestResponse : BaseResponse
{
public Test[] Tests { get; set; }
}
或者像这样将其添加到JsonSerializerSettings
:
var settings = new JsonSerializerSettings { Converters = new[] { new TestResponseConverter() } };
var response = JsonConvert.DeserializeObject<R>(responseText, settings);
原型小提琴。