我是c#newbie,我想通过使用 HttpClient 从API获得响应,并使用以下代码从下面显示的服务器获取JSON:
class Program
{
public class Parameter
{
public Usuario Usuario { get; set; }
public Establecimiento Establecimiento { get; set; }
}
public class Usuario
{
public string email { get; set; }
public string password { get; set; }
}
public class Establecimiento
{
public int id { get; set; }
}
public class deliveryData
{
public string id { get; set; }
public string establecimiento_id { get; set; }
public string numero_orden { get; set; }
public string ciudad_id { get; set; }
public string fecha { get; set; }
}
static void Main()
{
try
{
RunAsync().Wait();
Console.ReadLine();
}
catch (AggregateException e)
{
Console.WriteLine("Exception details: " + e.ToString());
Console.ReadLine();
}
}
static async Task RunAsync()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://it-215...web.development.co/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
try
{
// HTTP POST
var json = new Parameter
{
Establecimiento = new Establecimiento
{
id = 147
},
Usuario = new Usuario
{
email = "user@email.com",
password = "something"
}
};
HttpResponseMessage response = await client.PostAsJsonAsync("api/service", json);
response.EnsureSuccessStatusCode(); // Throw if not a success code.
string responseBodyAsText;
responseBodyAsText = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBodyAsText);
//List<Dictionary<string, deliveryData>> decodedDeliveries = JsonConvert.DeserializeObject<List<Dictionary<string, deliveryData>>>(responseBodyAsText);
//foreach (var delivery in decodedDeliveries)
//{
// Console.WriteLine(delivery.ToString());
//}
}
catch (HttpRequestException e)
{
Console.WriteLine("Exception details: " + e.ToString());
}
}
}
}
直到此处的JSON响应:
[ {
"PedidosOnline": {
"id": "7491031",
"establecimiento_id": "147",
"numero_orden": "1769629-20160509211442",
"fecha": "2016-05-09 21:14:42"
}
}, {
"PedidosOnline": {
"id": "7491328",
"establecimiento_id": "147",
"numero_orden": "1559397-20160509212644",
"fecha": "2016-05-09 21:26:44"
}
} ]
现在我评论
Console.WriteLine(responseBodyAsText);
并取消注释解码线和foreach,这就是我得到的:
System.Collections.Generic.Dictionary`2[System.String,ProjectName.Program+deliveryData]
System.Collections.Generic.Dictionary`2[System.String,ProjectName.Program+deliveryData]
我想要的是获得在JSON中查看的字段的干净打印,因为我的下一步是将字典中的每个字段保存在Access DB中(我不知道该怎么做但是我会想办法)。所以我需要一些帮助,任何建议都会得到很多赞赏。
非常感谢提前。
答案 0 :(得分:2)
不是打印Dictionary
个对象本身,而是遍历每个Dictionary
并打印每个键值对。
List<Dictionary<string, deliveryData>> decodedDeliveries = JsonConvert.DeserializeObject<List<Dictionary<string, deliveryData>>>(responseBodyAsText);
foreach (var delivery in decodedDeliveries)
{
foreach(var pair in delivery) {
Console.WriteLine(pair.Key + " : " + pair.Value);
}
}