When unity3d performs http Communication with net, the most common request is to submit the form data, but the server returns a piece of json data, this requires us to process json data in unity. Generally, LitJSON (which is
Unity3d. net, the most common request is the form data submission request, but the server returns a piece of json data, this requires us to process json data in unity. In general, LitJSON is the most commonly used for processing json data (it is.. net platform ). I will post the source code below for your reference!
Client:
using UnityEngine;using System.Collections;using LitJson;public class GetPhotoList : MonoBehaviour { // Use this for initialization void Start () { StartCoroutine(GetPhotos()); } // Update is called once per frame IEnumerator GetPhotos(){ WWWForm form = new WWWForm(); form.AddField(id,123); WWW w = new WWW(http://localhost:36944/GetPhotoList.ashx,form); while (!w.isDone){yield return new WaitForEndOfFrame();} if (w.error != null){Debug.LogError(w.error);} Debug.Log(w.text); JsonData jd = JsonMapper.ToObject(w.text); for (int i = 0; i < jd.Count; i++) { Debug.Log(id= + jd[i][id]); Debug.Log(name= + jd[i][name]); } }}
Server:
Using System; using System. collections. generic; using System. linq; using System. web; using System. runtime. serialization. json; using System. serviceModel; using System. serviceModel. web; using System. IO; namespace UpdatePhoto {////// Summary of GetPhotoList ///Public class GetPhotoList: IHttpHandler {public void ProcessRequest (HttpContext context) {context. response. contentType = text/plain; string id = context. request. form [id]; string path = context. request. physicalApplicationPath; // context. response. write (Hello World); List
Photos = GetPhotos (id, path); DataContractJsonSerializer djson = new DataContractJsonSerializer (photos. GetType (); djson. WriteObject (context. Response. OutputStream, photos);} public List
GetPhotos (string id, string path) {// obtain the directory string localPath = path + id + \; // read the files in the directory if (! Directory. Exists (localPath) return null; string [] files = Directory. GetFiles (localPath); List
Photos = new List
(); Foreach (string file in files) {string filename = file. substring (file. lastIndexOf ('\') + 1); Photo p = new Photo (); p. name = filename; p. id = id; photos. add (p) ;}return photos ;}public bool IsReusable {get {return false ;}} public class Photo {public string id; public string name ;}}