Unity C#如何使用Json Utility读取HTTP服务器的JSON数据
Hey there! Let's walk through this step by step—since you're new to Unity's JsonUtility, it's totally normal to get stuck on matching JSON structures to C# classes. Let's fix your parsing issue and get you access to that stock data.
Step 1: Create Serializable C# Classes Matching the JSON Structure
First, we need to define C# classes that exactly mirror the JSON response from the IEX API. Every class used for parsing must have the [Serializable] attribute—this tells Unity's JsonUtility that it can work with the class.
Root Stock Data Class
The top-level JSON has three keys: quote, news, and chart. We'll create a root class to hold all three:
using System.Collections.Generic; using UnityEngine; [Serializable] public class StockData { public Quote quote; public List<NewsItem> news; public List<ChartData> chart; }
Quote Class (Matches the quote JSON Object)
This class maps directly to the quote data you shared in your example:
[Serializable] public class Quote { public string symbol; public string companyName; public string primaryExchange; public string sector; public string calculationPrice; public float open; public long openTime; public float close; public long closeTime; public float high; public float low; public float latestPrice; public string latestSource; public string latestTime; public long latestUpdate; public long latestVolume; public float iexRealtimePrice; public int iexRealtimeSize; public long iexLastUpdated; public float delayedPrice; public long delayedPriceTime; public float previousClose; public float change; public float changePercent; public float iexMarketPercent; public long iexVolume; public long avgTotalVolume; public float iexBidPrice; public int iexBidSize; public float iexAskPrice; public int iexAskSize; public long marketCap; public float peRatio; public float week52High; public float week52Low; public float ytdChange; }
News Item Class (Matches news Array Entries)
The API returns a list of news items—here's a class to match those:
[Serializable] public class NewsItem { public string datetime; public string headline; public string source; public string url; public string summary; public string related; public string image; public string lang; public bool hasPaywall; }
Chart Data Class (Matches chart Array Entries)
For the 1-month chart data, use this class:
[Serializable] public class ChartData { public string date; public float open; public float high; public float low; public float close; public long volume; public float uOpen; public float uHigh; public float uLow; public float uClose; public long uVolume; public float change; public float changePercent; public float vwap; public string label; public float changeOverTime; }
Step 2: Update Your DataManager to Parse the JSON
Now let's modify your existing DataManager script to actually parse the JSON string into usable C# objects. We'll also fix a small inefficiency in how you set the URL.
Updated DataManager Code
using System.Collections; using System.Collections.Generic; using UnityEngine; public class DataManager : MonoBehaviour { public string Index_name; public string jsonString; // Remove the URL assignment from Update—no need to set it every frame! // void Update() { ... } public void Text_Changed(string newIndex) { Index_name = newIndex; } public void Request() { // Build the URL only when we need to make a request string requestUrl = $"https://api.iextrading.com/1.0/stock/{Index_name}/batch?types=quote,news,chart&range=1m&last=10"; WWW request = new WWW(requestUrl); StartCoroutine(OnResponse(request)); } private IEnumerator OnResponse(WWW req) { yield return req; // Check for request errors first if (!string.IsNullOrEmpty(req.error)) { Debug.LogError($"Request failed: {req.error}"); return; } jsonString = req.text; // Parse the JSON into our StockData object StockData stockData = JsonUtility.FromJson<StockData>(jsonString); // Test if parsing worked by logging some data if (stockData != null && stockData.quote != null) { Debug.Log($"Symbol: {stockData.quote.symbol}"); Debug.Log($"Latest Price: ${stockData.quote.latestPrice}"); Debug.Log($"Company: {stockData.quote.companyName}"); } // Log a sample news item if available if (stockData.news != null && stockData.news.Count > 0) { Debug.Log($"Top News: {stockData.news[0].headline}"); } } }
Key Tips to Remember
- Case Sensitivity: C# field names must exactly match the JSON keys (e.g.,
companyNamein JSON =companyNamein C#—notCompanyName). - Serializable Attribute: Don't forget
[Serializable]on every class used for parsing—JsonUtility ignores classes without it. - Arrays/Lists: JSON arrays (like
newsandchart) map to C#List<T>orT[]arrays—both work with JsonUtility. - WWW is Deprecated: For newer Unity versions, use
UnityWebRequestinstead ofWWW(it's more secure and efficient). Here's a quick replacement for the Request method:public void RequestWithUnityWebRequest() { string requestUrl = $"https://api.iextrading.com/1.0/stock/{Index_name}/batch?types=quote,news,chart&range=1m&last=10"; StartCoroutine(SendUnityWebRequest(requestUrl)); } private IEnumerator SendUnityWebRequest(string url) { using (UnityWebRequest webRequest = UnityWebRequest.Get(url)) { yield return webRequest.SendWebRequest(); if (webRequest.result != UnityWebRequest.Result.Success) { Debug.LogError($"Request failed: {webRequest.error}"); } else { jsonString = webRequest.downloadHandler.text; StockData stockData = JsonUtility.FromJson<StockData>(jsonString); // Use your parsed data here! } } }
内容的提问来源于stack exchange,提问作者Bruck Film

