2017-01-16 2 views
0

私はC#を初めてお使いになりました。JSONをGETリクエストからC#Winformsアプリケーションのテキストボックスに変換してください。

会社に関する情報を得るために会社のハウスAPIを利用するコード(下記)を書きました。情報はJSON形式で返されます。

私が必要とするのは、特定の情報を取って、すでにフォーム上にあるテキストボックスに入れます。私が書いたコードは、メッセージボックスに戻すことができますが、テキストボックスに入力する方法を考えることはできません。私は次の私のコードを更新しました

{ 
"accounts":{ 
"accounting_reference_date":{ 
"month":"12", 
"day":"31" 
}, 
"last_accounts":{ 
"type":"group", 
"made_up_to":"2015-12-31" 
}, 
"next_made_up_to":"2016-12-31", 
"next_due":"2017-09-30", 
"overdue":false 
}, 
"company_number":"08867781", 
"annual_return":{ 
"last_made_up_to":"2016-06-20", 
"overdue":false 
}, 
"jurisdiction":"england-wales", 
"has_been_liquidated":false, 
"date_of_creation":"2014-01-29", 
"undeliverable_registered_office_address":false, 
"company_name":"VIRGIN ATLANTIC LIMITED", 
"registered_office_address":{ 
"address_line_2":"Fleming Way", 
"locality":"Crawley", 
"country":"United Kingdom", 
"region":"West Sussex", 
"address_line_1":"Company Secretariat - The VHQ", 
"postal_code":"RH10 9DF" 
}, 
"type":"ltd", 
"last_full_members_list_date":"2016-06-20", 
"sic_codes":[ 
"70100" 
], 
"has_insolvency_history":false, 
"etag":"cbab10bb8b9dc1db442cb585a63ae208c1265100", 
"company_status":"active", 
"has_charges":false, 
"previous_company_names":[ 
{ 
"name":"VIRGIN ATLANTIC (HOLDINGS) LIMITED", 
"effective_from":"2014-01-29", 
"ceased_on":"2014-05-30" 
} 
], 
"confirmation_statement":{ 
"next_made_up_to":"2017-06-20", 
"overdue":false, 
"next_due":"2017-07-04" 
}, 
"links":{ 
"self":"/company/08867781", 
"filing_history":"/company/08867781/filing-history", 
"officers":"/company/08867781/officers" 
}, 
"registered_office_is_in_dispute":false, 
"can_file":true 
} 

** UPDATE **

private void getFromCompaniesHouse(object sender, EventArgs e) 
    { 
     try 
     { 
      //Compile request url 
      string url = "https://api.companieshouse.gov.uk/company/" + txtCompanyNumber.Text; 

      // Encode API key to ASCII 
      string api_key = "yfhOb66cRn7ZL1VgdFjVur5cs8u6j__bcNnKj9Qs:"; 
      string encodedKey = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(api_key)); 

      // Make get request using url and encoded API key 
      HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); 
      request.Method = "GET"; 
      request.Headers.Add("Authorization", "Basic " + encodedKey); 
      request.ContentType = "application/json; charset=utf-8"; 

      var response = (HttpWebResponse)request.GetResponse(); 
      var rawJson = new StreamReader(response.GetResponseStream()).ReadToEnd(); 

      var json = JObject.Parse(rawJson); //Turns your raw string into a key value lookup 
      string company_name = json["company_name"].ToObject<string>(); 

      txtBusinessName.Text = company_name; 

     } 
     catch 
     { 
      MessageBox.Show("Cannot Make Request", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); 
     } 
    } 

私は物事を引くことができますJSONが返さ

private void getFromCompaniesHouse(object sender, EventArgs e) 
    { 
     try 
     { 
      //Compile request url 
      string url = "https://api.companieshouse.gov.uk/company/" + txtCompanyNumber.Text; 

      // Encode API key to ASCII 
      string api_key = "yfhOb66cRn7ZL1VgdFjVur5cs8u6j__bcNnKj9Qs:"; 
      string encodedKey = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(api_key)); 

      // Make get request using url and encoded API key 
      HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); 
      request.Method = "GET"; 
      request.Headers.Add("Authorization", "Basic " + encodedKey); 
      request.ContentType = "application/json; charset=utf-8"; 

      var response = (HttpWebResponse)request.GetResponse(); 

      using (var streamReader = new StreamReader(response.GetResponseStream())) 
      { 
       MessageBox.Show(streamReader.ReadToEnd()); 
      } 
     } 
     catch 
     { 
      MessageBox.Show("Cannot Make Request", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); 
     } 
    } 

は次のようになりますRootObjectクラスからアクセスしましたが、例えばのようなものにはアクセスできませんクラス。何か案は?

+0

JSONは「特定の情報」がある場合、同じようおよび/またはあなたの場合に見えるものを知らずに手助けするのは難しいですそれを逆シリアル化する方法を理解してください – Plutonix

+0

JSONのために定義された構造体がありますか? – Eric

+0

ここにはいくつかのステップがあります。一般的に、JSONをC#クラス(Google C#deserialize jsonなど)に変換するライブラリを使用したい場合は、通常はテキストを設定するのと同じように、そこから情報を取り出してテキストボックスに貼り付けることができます。 – mmcrae

答えて

0

ここにあなたの会社の情報にアクセスする(JSON.NETを使用して)サンプルのコンソールアプリだ:

using System; 
using System.Collections.Generic; 
using System.Net.Http; 
using System.Net.Http.Headers; 
using System.Text; 
using System.Threading.Tasks; 
using Newtonsoft.Json; 

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      var task = GetFromCompaniesHouse(); 

      task.Wait(); 

      Console.WriteLine("Press any key to exit..."); 
      Console.ReadKey(); 
     } 

     private static async Task GetFromCompaniesHouse() 
     { 
      var url = "https://api.companieshouse.gov.uk/company/08867781"; 
      var apiKey = "yfhOb66cRn7ZL1VgdFjVur5cs8u6j__bcNnKj9Qs:"; 
      var encodedKey = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(apiKey)); 

      using (var client = new HttpClient()) 
      { 
       var request = new HttpRequestMessage(HttpMethod.Get, url); 

       request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 
       request.Headers.Add("Authorization", $"Basic {encodedKey}"); 

       var response = await client.SendAsync(request); 
       var content = await response.Content.ReadAsStringAsync(); 
       var company = JsonConvert.DeserializeObject<Company>(content); 

       Console.WriteLine($"Company: {company.company_name}"); 
      } 
     } 
    } 

    public class LastAccounts 
    { 
     public string made_up_to { get; set; } 
     public string type { get; set; } 
    } 

    public class AccountingReferenceDate 
    { 
     public string month { get; set; } 
     public string day { get; set; } 
    } 

    public class Accounts 
    { 
     public LastAccounts last_accounts { get; set; } 
     public string next_due { get; set; } 
     public bool overdue { get; set; } 
     public string next_made_up_to { get; set; } 
     public AccountingReferenceDate accounting_reference_date { get; set; } 
    } 

    public class RegisteredOfficeAddress 
    { 
     public string region { get; set; } 
     public string locality { get; set; } 
     public string address_line_2 { get; set; } 
     public string postal_code { get; set; } 
     public string address_line_1 { get; set; } 
    } 

    public class PreviousCompanyName 
    { 
     public string effective_from { get; set; } 
     public string name { get; set; } 
     public string ceased_on { get; set; } 
    } 

    public class ConfirmationStatement 
    { 
     public string last_made_up_to { get; set; } 
     public string next_made_up_to { get; set; } 
     public string next_due { get; set; } 
     public bool overdue { get; set; } 
    } 

    public class Links 
    { 
     public string self { get; set; } 
     public string filing_history { get; set; } 
     public string officers { get; set; } 
     public string charges { get; set; } 
    } 

    public class Company 
    { 
     public Accounts accounts { get; set; } 
     public string company_name { get; set; } 
     public bool has_been_liquidated { get; set; } 
     public RegisteredOfficeAddress registered_office_address { get; set; } 
     public string status { get; set; } 
     public string last_full_members_list_date { get; set; } 
     public string date_of_creation { get; set; } 
     public List<string> sic_codes { get; set; } 
     public bool undeliverable_registered_office_address { get; set; } 
     public string type { get; set; } 
     public string company_number { get; set; } 
     public string jurisdiction { get; set; } 
     public bool has_insolvency_history { get; set; } 
     public string etag { get; set; } 
     public string company_status { get; set; } 
     public bool has_charges { get; set; } 
     public List<PreviousCompanyName> previous_company_names { get; set; } 
     public ConfirmationStatement confirmation_statement { get; set; } 
     public Links links { get; set; } 
     public bool registered_office_is_in_dispute { get; set; } 
     public bool can_file { get; set; } 
    } 
} 
+0

ありがとうございますが、私は自分のコードでこれをどのように実装するのか分かりません。 私はcompany_nameを引き出し、それをtxtBusiness_Name.Textというテキストボックスに入れたいとします。 – user1948851

+0

データバインディングをカウントしない: txtBusiness_Name.Text = company.company_name; – Eric

+0

私は上記のように自分のコードを更新しましたが、RootObject以外のものにはアクセスできません。 – user1948851

関連する問題