如何使用C#.Net存储不同响应类型的API结果集

时间:2018-08-09 07:21:11

标签: c# asp.net-web-api

我正在尝试调用两个API并存储它们的响应。 下面是API响应类型:

API1响应:

{
  "Name": "Apple",
  "Expiry": "2008-12-28T00:00:00",
 "Price": 3.99,
 "Sizes": [
 "Small",
 "Medium",
 "Large"
  ]
}

API2响应:

["Name=xyz, Id=1, Version=1","Name=abc, Id=1, Version=2","Name=hgf, Id=1, Version=3","Name=utgds, Id=1, Version=4","Name=kfgf, Id=2, Version=1"]

下面是调用API并获取结果集的代码。

var jsonObj = Get<SomeClass>("API_URL1");
var jsonObj2 = Get<Test>("API_URL2");

 public T Get<T>(string requestUri)
        {
            T response = default(T);
            using (var handler = new HttpClientHandler { Credentials = CredentialCache.DefaultNetworkCredentials })
            {
                using (var httpClient = CreateNewRequest(handler))
                {
                    var httpTask = httpClient.GetAsync(requestUri);
                    var response = task.Result;
                    response.EnsureSuccessStatusCode();
                    if (response.IsSuccessStatusCode)
                    {
                        var result = response.Content.ReadAsStringAsync().Result;
                        var res = JsonConvert.DeserializeObject<T>(result);

                    }
                }
            }
            return res;
        }

 private HttpClient CreateNewRequest(HttpClientHandler handler)
    {
        HttpClient client = new HttpClient(handler);
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        return client;
    }

public class Test
{
    public string Name { get; set; }
    public int Id { get; set; }
    public int Version { get; set; }


}

类似地,我创建了一个类来保存API1响应。 我能够存储API1响应,但是在存储API2响应时却收到此错误消息。

  

无法将当前JSON数组(例如[1,2,3])反序列化为type   因为该类型需要一个JSON对象(例如{“ name”:“ value”})   正确反序列化。要解决此错误,请将JSON更改为   JSON对象(例如{“ name”:“ value”})或将反序列化类型更改为   实现集合接口的数组或类型。

对此有任何想法/提示吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

我测试了我在评论中所说的内容。第二个响应是字符串的JSON数组。您应该将其反序列化为字符串数组(string[])或字符串集合(List<string>)。预期效果如下:

var response = "[\"Name=xyz, Id=1, Version=1\", \"Name=abc, Id=1, Version=2\", \"Name=hgf, Id=1, Version=3\", \"Name=utgds, Id=1, Version=4\", \"Name=kfgf, Id=2, Version=1\"]";
var result = JsonConvert.DeserializeObject<string[]>(response);

总结一下:使用Get<Test>代替Get<string[]>。您只需要解析字符串,但这似乎是另一个问题。


下面的完整演示(故意嘲笑网址调用):

class Program
{
    static void Main(string[] args)
    {
        var invoker = new JsonMockInvoker();
        var jsonObj = invoker.Get<SomeClass>("API_URL1");
        var jsonObj2 = invoker.Get<string[]>("API_URL2");
    }
}

class SomeClass
{
    public string Name { get; set; }
    //other properties
}

public class JsonMockInvoker:JsonInvoker
{
    public override string InvokeRest(string url)
    {
        if (url == "API_URL1")
            return "{\"Name\": \"Apple\",\"Expiry\": \"2008-12-28T00:00:00\",\"Price\": 3.99,\"Sizes\": [\"Small\",\"Medium\",\"Large\"]}";
        if (url == "API_URL2")
            return "[\"Name=xyz, Id=1, Version=1\", \"Name=abc, Id=1, Version=2\", \"Name=hgf, Id=1, Version=3\", \"Name=utgds, Id=1, Version=4\", \"Name=kfgf, Id=2, Version=1\"]";
        throw new NotImplementedException();
    }
}

public class JsonInvoker
{
    public T Get<T>(string requestUri)
    {
        var result = InvokeRest(requestUri);
        return result != null ? JsonConvert.DeserializeObject<T>(result) : default(T);
    }

    public virtual string InvokeRest(string url)
    {
        using (var handler = new HttpClientHandler { Credentials = CredentialCache.DefaultNetworkCredentials })
        using (var httpClient = CreateNewRequest(handler))
        {
            var httpTask = httpClient.GetAsync(url);
            var response = httpTask.Result;
            response.EnsureSuccessStatusCode();
            if (response.IsSuccessStatusCode)
            {
                return response.Content.ReadAsStringAsync().Result;
            }
        }
        return null;
    }

    private HttpClient CreateNewRequest(HttpClientHandler handler)
    {
        HttpClient client = new HttpClient(handler);
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        return client;
    }
}

字符串值不是JSON格式-您必须手动解析它们:

//parse to typed object
var parsedObject = jsonObj2.Select(a => new
{
    Id = Regex.Match(a, "(?<=Id=)[^,]*").Value,
    Name = Regex.Match(a, "(?<=Name=)[^,]*").Value
});

//parse to dictionary
var regex = new Regex("([\\s]|^)(?<key>[^=]+)=(?<value>[^,]*)");
var parsed = jsonObj2.Select(a =>
{
    var dictionary = new Dictionary<string, string>();
    foreach (Match match in regex.Matches(a))
        dictionary[match.Groups["key"].Value] = match.Groups["value"].Value;
    return dictionary;
});