unity requests json data and parses it

When unity3d is communicating with. net over http, the most common thing is to submit the form data request, but the ser...

When unity3d is communicating with. net over http, the most common thing is to submit the form data request, but the server will return a lump of json data, which requires us to process the json data in unit. Generally, the most common way to process the json data in unit is litjson (it is the class library that processes the SON database under the. net platform). Below I post the source code, only for learning reference!

For the installation and use of LitJSON, please refer to: http://www.360doc.com/content/13/0117/11/10941785_260686840.shtml

Or refer to: http://blog.csdn.net/dingxiaowei2013/article/details/17115665


Put LitJson.dll in the plugins file in the assets directory. If there is no plugins file, create one manually


Client:

  1. using UnityEngine;
  2. using System.Collections;
  3. using LitJson;
  4. public class GetPhotoList : MonoBehaviour {
  5. // Use this for initialization
  6. void Start () {
  7. StartCoroutine(GetPhotos());
  8. }
  9. // Update is called once per frame
  10. IEnumerator GetPhotos(){
  11. WWWForm form = new WWWForm();
  12. form.AddField("id","123");
  13. WWW w = new WWW("http://localhost:36944/GetPhotoList.ashx",form);
  14. while (!w.isDone)
  15. if (w.error != null)
  16. Debug.Log(w.text);
  17. JsonData jd = JsonMapper.ToObject(w.text);
  18. for (int i = 0; i < jd.Count; i++)
  19. {
  20. Debug.Log("id=" + jd[i]["id"]);
  21. Debug.Log("name=" + jd[i]["name"]);
  22. }
  23. }
  24. }

Server:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Runtime.Serialization.Json;
  6. using System.ServiceModel;
  7. using System.ServiceModel.Web;
  8. using System.IO;
  9. namespace UpdatePhoto
  10. {
  11. /// <summary>
  12. ///Summary description for GetPhotoList
  13. /// </summary>
  14. public class GetPhotoList : IHttpHandler
  15. {
  16. public void ProcessRequest(HttpContext context)
  17. {
  18. context.Response.ContentType = "text/plain";
  19. string id = context.Request.Form["id"];
  20. string path = context.Request.PhysicalApplicationPath;
  21. //context.Response.Write("Hello World");
  22. List<Photo> photos = GetPhotos(id,path);
  23. DataContractJsonSerializer djson = new DataContractJsonSerializer(photos.GetType());
  24. djson.WriteObject(context.Response.OutputStream, photos);
  25. }
  26. public List<Photo> GetPhotos(string id,string path)
  27. {
  28. //Get directory
  29. string localPath = path+id + "\\;
  30. 11 May 2020, 12:53 | Views: 9802

    Add new comment

    For adding a comment, please log in
    or create account

    0 comments