How to read JSON data from a web service in C#
How to read a JSON data from a web service in Unity. This Tutorial is about reading JSON data. We will build a little application build on a JSON webservice.
✅ Download the free SimpleJSON parser:
https://github.com/HenrikPoulsen/SimpleJSON
✅ The free geoplugin webservice:
http://www.geoplugin.net/json.gp?ip=213.22.22.98
❤️ Subscribe to Oxmond Tutorials. New tutorials every day! Stay tuned!
https://bit.ly/SubscribeOxmondTutorials
🔔 Remember to hit that little bell to turn on notifications!
😷👕 Need a face mask / developer T-shirt? Drop by our shop and get a 20% DISCOUNT on your first purchase by using the discount code OXMONDSALE. Click here:
https://shop.oxmond.com/discount/OXMONDSALE
✅ Download free assets from the Unity Assets Store for your game:
https://assetstore.unity.com/lists/top-free-packages-13201?aid=1100l4p9k
The LoadJSON script:
/*
.-------. .--. .-------. .--. .--. .--.
| |--.--.--------.-----.-----.--| | |_ _|--.--| |_.-----.----|__|---.-| |-----.
| - |_ _| | _ | | _ | | | | | | _| _ | _| | _ | |__ --|
|_______|__.__|__|__|__|_____|__|__|_____| |___| |_____|____|_____|__| |__|___._|__|_____|
© 2019 OXMOND / www.oxmond.com
*/
using System.Collections;
using UnityEngine;
using SimpleJSON;
using UnityEngine.Networking;
using TMPro;
public class LoadJSON : MonoBehaviour
{
public TMP_InputField inputTxt;
public TMP_Text countryTxt;
public TMP_Text continentTxt;
public void GetJsonData()
{
StartCoroutine(RequestWebService());
}
IEnumerator RequestWebService()
{
string getDataUrl = "http://www.geoplugin.net/json.gp?ip=" + inputTxt.text;
print(getDataUrl);
using (UnityWebRequest webData = UnityWebRequest.Get(getDataUrl))
{
yield return webData.SendWebRequest();
if (webData.isNetworkError || webData.isHttpError)
{
print("---------------- ERROR ----------------");
print(webData.error);
}
else
{
if (webData.isDone)
{
JSONNode jsonData = JSON.Parse(System.Text.Encoding.UTF8.GetString(webData.downloadHandler.data));
if (jsonData == null)
{
print("---------------- NO DATA ----------------");
}
else
{
print("---------------- JSON DATA ----------------");
print("jsonData.Count:" + jsonData.Count);
countryTxt.text = jsonData["geoplugin_countryName"];
continentTxt.text = jsonData["geoplugin_continentName"];
}
}
}
}
}
}
Hello,
Do you have the same script but with UnityWebRequest.post ?
Thank you so much.
Best regards
Steve