1 回答
TA贡献1797条经验 获得超6个赞
我测试了我在评论中所说的。第二个响应是字符串的 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[]>. 您只需要解析字符串,但这似乎是另一个问题。
下面的完整演示(故意嘲笑 url 调用):
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;
});
- 1 回答
- 0 关注
- 173 浏览
添加回答
举报