【发布时间】:2016-01-09 18:32:26
【问题描述】:
我正在尝试使用在线 API 根据 UPC 代码检索数据,然后将其转换为对象。他们的方法之一是获取 JSON 格式的数据。
你得到的结果是这样的:
{
"0": {
"productname": "Play-doh Single Can by Hasbro",
"imageurl": "http://ecx.images-amazon.com/images/I/31ZzLhzYDEL._SL160_.jpg",
"producturl": "",
"price": "10.01",
"currency": "GBP",
"saleprice": "",
"storename": "N/A"
},
"1": {
"productname": "PLAY-DOH Compound Tropical Pink - Two, 5 oz Cans (10 oz)",
"imageurl": "http://ecx.images-amazon.com/images/I/51LbjiXtEjL._SL160_.jpg",
"producturl": "",
"price": "37.07",
"currency": "GBP",
"saleprice": "",
"storename": "N/A"
}
}
我在 8.1 应用程序中使用 .NET C# 4.5.2。我正在尝试使用 HttpClient,但我不断得到奇怪的结果,好像 JSON 格式不正确。我将它放入在线 Json 编辑器中,看起来不错,所以我不确定问题出在哪里。我正在运行的代码非常简单。看起来像这样。
public async Task<string> GetUpc(string upcCode)
{
var url = "http://www.searchupc.com/handlers/";
var result = string.Empty;
using (HttpClient client = new HttpClient())
{
// client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync("http://www.searchupc.com/handlers/upcsearch.ashx?request_type=3&access_token=MY_TOKEN&upc=0653569289791");
result = await response.Content.ReadAsStringAsync();
//JToken token = await Task.Run(() => JObject.Parse(reader.ReadLine()));
//string name = (string)token.SelectToken("productname");
JsonSerializer s = new JsonSerializer();
var i = JsonConvert.DeserializeObject<dynamic>(result);
}
return result;
}
当我检查“i”时,它只是 API 结果的字符串表示形式。我还尝试使用 JsonConvert.DeserializeObject 并将字符串传递给它,但它仍然只是返回一个一遍又一遍地具有字符串表示的对象。好像知道是json对象但是格式不对。
目前我想到的唯一解决方案是使用 JObject.Parse 作为标记,然后使用 SelectToken 遍历树。
有什么想法吗?解决方案感觉不对。
【问题讨论】:
标签: c# json api dotnet-httpclient