JArray对象具有数组属性

时间:2016-03-17 12:34:40

标签: c# json json.net

我有一个使用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返回错误请求等时,HasErrorMessage会有一个值。

任何信息将不胜感激。谢谢。

1 个答案:

答案 0 :(得分:0)

从您的评论中,听起来似乎成功的响应将显示为JSON数组,但如果发生错误,则将返回带有错误标志和消息的JSON对象。为了解析两个可能的响应,您可以创建一个custom 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);

原型fiddle