2016-06-09 3 views
1

나는 교류 # 초보자와 나는 HttpClient를 아래 그림 I는 서버에서 JSON을 가지고 다음 코드를 사용하여 API의 응답을 얻기 위해 알아 냈 : 여기까지목록 사전을 반복하고 내용을 인쇄하는 방법?

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 = "[email protected]", 
         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 응답 :

을 나는

Console.WriteLine (responseBodyAsText를) 언급 이제

[ { 
    "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" 
    } 
} ] 

;

System.Collections.Generic.Dictionary`2[System.String,ProjectName.Program+deliveryData] 
System.Collections.Generic.Dictionary`2[System.String,ProjectName.Program+deliveryData] 

내가 원하는 것은 내 다음 단계이기 때문에, JSON에서 본 필드의 깨끗한 인쇄를 얻을 수 있습니다 :

및 디코딩 라인과 foreach는 주석을 제거

이 내가 무엇을 얻을 액세스 DB에있는 사전의 모든 필드를 저장하는 방법에 대해서는 잘 모릅니다.하지만 알아낼 것입니다. 그래서 약간의 도움이 필요합니다. 어떤 충고라도 감사하게 받아 들일 것입니다.

미리 감사드립니다.

+4

http://stackoverflow.com/questions/14719955/looping-through-dictionary-object 당신은 >>'하는'목록 ​​<사전 <문자열로 deliverydata를 역 직렬화하는 – MethodMan

+0

은? 'Dictionary '를 의미하지 않습니까? 그런 다음 그냥'Console.WriteLine (item.key + ""+ item.value); ' –

+1

@MethodMan을 인쇄하려면 개인적으로 [this] (http://stackoverflow.com/a/141098/6352535) 대답을 권하고 싶습니다./thread 대신 –

답변

1

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); 
    } 
} 
+0

원하는 경우 루프 내에서 추가 인쇄물을 추가하여 JSON 형식으로 인쇄 할 수도 있습니다. –

+0

답장을 보내 주셔서 감사합니다.이 질문에 대한 답변은 효과가있었습니다. 나는 당신의 대답을 upvote 명성을 얻을 때 upvote 것입니다. –

+0

@andres_v 그것을 듣고 다행스럽게도 내 답변을 올바른 것으로 표시 할 수 있습니까? –

관련 문제