반응형

* C# Json Parsing 을 이용한 로또 (Lotto) 당첨 번호 읽어 오기 예제...

 

메인화면

 

전체 소스 코드

Form1.cs

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Net.Json;
using System.Net;
using System.IO;

namespace CSharp_JsonParsing
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        #region 사용자 정의 함수...
        private string GetHttpLottoString(string strUri)
        {
            string strResponseText = string.Empty;

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strUri);
            request.Method = "GET";

            //웹리퀘스트 타임아웃 
            request.Timeout = 20 * 1000; // 20초
            //request.Headers.Add("Authorization", "BASIC SGVsbG8="); // 헤더 추가 방법

            //응답 받기
            using (HttpWebResponse hwr = (HttpWebResponse)request.GetResponse())
            {
                //응답이 정상적으로 이루어 졌으면... 
                if (hwr.StatusCode == HttpStatusCode.OK)
                {
                    Stream respStream = hwr.GetResponseStream();
                    using (StreamReader sr = new StreamReader(respStream))
                    {
                        strResponseText = sr.ReadToEnd();
                    }
                }
                else
                {
                    strResponseText = "";
                }
            }

            return strResponseText;
        }

        private bool IsNullString(string str)
        {
            return string.IsNullOrEmpty(str);
        }

        private int IsInt(object ob)
        {
            if (ob == null) return 0;

            int iCheck = 0;
            bool bCheck = int.TryParse(ob.ToString(), out iCheck);

            if (!bCheck)
            {
                return 0;
            }

            return iCheck;
        }
        #endregion

        private void button2_Click(object sender, EventArgs e)
        {
            //LotNo 불러오기...
            /*
                returnValue : json 결과값 (success 또는 fail)
                totSellamnt : 누적 상금
                drwNo : 로또회차
                drwNoDate : 로또당첨일시
                firstWinamnt : 1등 당첨금
                firstPrzwnerCo : 1등 당첨 인원
                firstAccumamnt : 1등 당첨금 총액
                drwtNo1 : 로또번호1
                drwtNo2 : 로또번호2
                drwtNo3 : 로또번호3
                drwtNo4 : 로또번호4
                drwtNo5 : 로또번호5
                drwtNo6 : 로또번호6
                bnusNo  : 보너스번호 
             */

            //빈값이거나 null 값이면...
            if (IsNullString(textBox1.Text))
            {
                MessageBox.Show("빈 값일 순 없습니다.");
                return;
            }

            //숫자가 아니면...
            if (IsInt(textBox1.Text) == 0)
            {
                MessageBox.Show("숫자만 입력 해 주세요.");
                return;
            }

            //로또 회차 넘버 불러오기...
            string strReturnValue = GetHttpLottoString("https://www.dhlottery.co.kr/common.do?method=getLottoNumber&drwNo=" + textBox1.Text );

            if (strReturnValue == "")
            {
                MessageBox.Show("Lotto Number 불러오기 실패...");
                return;
            }

            //Json 으로 바꾸기...
            JsonTextParser jtr = new JsonTextParser();
            JsonObject jo = jtr.Parse(strReturnValue);

            JsonObjectCollection jac = (JsonObjectCollection)jo;

            //불러오기가 성공 하면...
            textBox2.Text = "";
            if (jac["returnValue"].GetValue().ToString() == "success")
            {
                //텍스트 박스에 뿌려주기...
                textBox2.Text += "로또 당첨일: " + jac["drwNoDate"].GetValue().ToString() + System.Environment.NewLine;
                textBox2.Text += "로또 회차: " + jac["drwNo"].GetValue().ToString() + System.Environment.NewLine + System.Environment.NewLine;
                textBox2.Text += "1등 당첨금: " + jac["firstWinamnt"].GetValue().ToString() + System.Environment.NewLine;
                textBox2.Text += "1등 당첨 인원: " + jac["firstPrzwnerCo"].GetValue().ToString() + " 명" + System.Environment.NewLine;
                textBox2.Text += "누적 상금: " + jac["totSellamnt"].GetValue().ToString() + System.Environment.NewLine + System.Environment.NewLine;
                textBox2.Text += "당첨 번호: " + jac["drwtNo1"].GetValue().ToString()
                                       + "," + jac["drwtNo2"].GetValue().ToString()
                                       + "," + jac["drwtNo3"].GetValue().ToString()
                                       + "," + jac["drwtNo4"].GetValue().ToString()
                                       + "," + jac["drwtNo5"].GetValue().ToString()
                                       + "," + jac["drwtNo6"].GetValue().ToString() + System.Environment.NewLine;
                textBox2.Text += "보너스 번호: " + jac["bnusNo"].GetValue().ToString() + System.Environment.NewLine;
            }

            
        }

        private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            //사용자가 엔터키를 입력 하면...
            if (e.KeyCode == Keys.Enter)
            {
                //버튼 클릭 이벤트 함수 호출 하기...
                button2_Click(null, null);
            }
        }



    }
}

로또 (Lotto) 당첨 번호 응답 받기 함수
버튼 이벤트 안 내용

* 예제 결과

 

결과 화면

 

↓ 참조 문서

 

https://kdsoft-zeros.tistory.com/97

 

[C#] Json File Write & Read 예제

* C# Json 파일 읽기 쓰기 예제... (System.Net.Json.dll) 파일 참조 위 첨부된 파일을 다운 받아 dll 참조 추가를 해줍니다. 오른쪽에 솔루션 탐색기가 나타나지 않는다면, 상단 메뉴 (보기) -> (솔루션탐색기)..

kdsoft-zeros.tistory.com

https://kdsoft-zeros.tistory.com/76

 

[C#] string 을 int 및 double 형으로 변환 하기, null 체크

* string 문자열을 정수 및 실수 형으로 변환 하기 예제... 전체 소스코드 Form1.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing;..

kdsoft-zeros.tistory.com

 

반응형

+ Recent posts