unity3d c# http 請求json數據解析


 1 using System.Collections;
 2 using System.Collections.Generic;
 3 using UnityEngine;
 4 using UnityEngine.Networking;
 5 using LitJson;
 6 using System.IO;
 7 using System.Net;
 8 
 9 
10 public class Connet : MonoBehaviour {
11 
12     //private ArrayList List = new ArrayList(5);
13     //private Rect rect = new Rect(10, 50, 150, 150);
14     //請求地址,寫自己的請求地址就行
15     private string url = "http://xxxxxxxxx/ApiServlet?method=list";
16     //聲明 JsonData     LitJson 提供的方法
17     JsonData itemdata;
18     //新建 List 存放數據
19     private List<Item> dataBase = new List<Item>();
20 
21     IEnumerator Start()
22     {
23         
24         WWW getData = new WWW(url);
25         yield return getData;
26         
27         if (getData.error != null)
28         {
29             Debug.Log(getData.error);
30         }
31         else
32         {
33             Debug.Log(getData.text);
34         }
35         //把請求到的數據轉換成 JsonData array 類型,並存儲到itemdata里
36         itemdata = JsonMapper.ToObject(getData.text);
37         //Debug.Log(itemdata);
38         //調用 ConstructItemDatabase() 函數
39         ConstructItemDatabase();
40         //測試數據
41         Debug.Log(dataBase[0].Name);
42     }
43     void ConstructItemDatabase()
44     {
45         //循環取數據
46         for (int i = 0; i < itemdata.Count; i++)
47         {
48             //把每個數據都添加到 dataBase 里  要和請求到的json數據對應
49             dataBase.Add(new Item((int)itemdata[i]["longId"], (int)itemdata[i]["intId"], itemdata[i]["item"].ToString()));
50         }
51     }
52 }
53 
54 //新建Item類
55 public class Item
56 {
57     //定義Item內的數據
58     //固定寫法 XX{ get; set; }
59     public int ID { get; set; }
60     public int IntId { get; set; }
61     public string Name { get; set; }
62 
63     //接收上面的變量
64     public Item(int _longId, int _intId, string _name)
65     {
66         ID = _longId;
67         IntId = _intId;
68         Name = _name;
69     }
70 }

LitJson.dll下載地址

提取碼:1znp

前一段時間一直糾結unity連接數據庫請求數據,浪費了不少時間。后來改用http請求,順利拿到數據,然后就着手於解析數據,就有了這篇文章

如果大家看不懂,這里有一個視頻講的還是相當詳細的


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM