动态解析json消息到poco对象

时间:2014-11-07 22:01:50

标签: c# json.net

我有这个方法将json响应消息解析为特定的poco对象。

是否可以通过在运行时添加classtype并将此方法用于多个类的方式进行更改。

private static async Task<TestClass> ParseResponseMessageToObject(HttpResponseMessage responseMessage)
{
    if (!responseMessage.IsSuccessStatusCode) { return null; }

    using (Stream responseStream = await responseMessage.Content.ReadAsStreamAsync())
    {
        return (TestClass)JsonConvert.DeserializeObject(new StreamReader(responseStream).ReadToEnd(), typeof(TestClass));
    }
}

2 个答案:

答案 0 :(得分:2)

我想你想要这样的东西

private static async Task<T> ParseResponseMessageToObject<T>(HttpResponseMessage responseMessage)
{
    if (!responseMessage.IsSuccessStatusCode) { return default(T); }

    using (Stream responseStream = await responseMessage.Content.ReadAsStreamAsync())
    {
        return JsonConvert.DeserializeObject<T>(new StreamReader(responseStream).ReadToEnd());
    }
}

如果您在编译时不知道您使用的类型,则可以使用动态

dynamic dynObj = JsonConvert.DeserializeObject(jsonstring);
int i = dynObj.SomeIntProperty

由于JObject实现了IDictionary,因此您也可以将其用作

var  dynObj = JObject.Parse(jsonstring);
int i = (int)dynObj["SomeIntProperty"];

答案 1 :(得分:0)

您应该将您的方法更改为更通用的

private static async Task<T> ParseResponseMessageToObject<T>(HttpResponseMessage responseMessage) where T : class, new()
    {
        if (!responseMessage.IsSuccessStatusCode) { return null; }

        using (Stream responseStream = await responseMessage.Content.ReadAsStreamAsync())
        {
            return (T)JsonConvert.DeserializeObject(new StreamReader(responseStream).ReadToEnd(), typeof(T));
        }
    }