본문 바로가기
Unity3D

[Unity 3D] UnityWebRequest.Get로 받아온 JSON 데이터를 처리하는 방법

by 따봉이 2020. 12. 17.
728x90
반응형

Unity에서 GetUnityWebRequest.Get로 받아온 JSON 데이터를 간단히 처리하는 방법을 정리해보았다.

 

- 실행환경

Unity : 2017.4.40f1
OS : Windows 10 Home 2004

 

 

2가지 방법이 있다.

 

MiniJSON을 사용하는 방법과

JsonUtility를 사용하는 방법.

 

MiniJSON와 JsonUtility는 큰 차이가 있다. 

MiniJSON은 JSON형식의 구조를 사전에 선언할 필요가 없다.

JsonUtility는 사전에 선언이 필요하다.

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using MiniJSON;

public class GetRequestWithJSON : MonoBehaviour
{
    public string uri = "http://weather.livedoor.com/forecast/webservice/json/v1?city=130010";

    void Start()
    {
        StartCoroutine(GetRequest(this.uri));
    }

    private IEnumerator GetRequest(string uri)
    {
        Debug.Log("-------- GET Request Start --------");
        using (UnityWebRequest request = UnityWebRequest.Get(uri))
        {
            yield return request.SendWebRequest();
            if (request.isNetworkError || request.isHttpError)
            {
                Debug.Log("GET Request Failure");
                Debug.Log(request.error);
            }
            else
            {
                Debug.Log("GET Request Success");
                Debug.Log(request.downloadHandler.text);
                Dictionary<string, object> response = Json.Deserialize(request.downloadHandler.text) as Dictionary<string, object>;
                Debug.Log(response["title"]);
            }
        }
    }
}

 

위 코드는 에러가 발생한 경우 에러를 표시하고 에러가 발생하지 않는 경우는 받아온 JSON 데이터를 표시하도록 한 것이다.

 

실행결과

 

728x90
반응형

댓글