I'm pretty new to c# and unity i'm trying to create a class able to talk with an external server via json API.
It was fine until I saw the code and I was repeating the same pieces over and over (basically each method of the API had its Ienumerator function with the JSON.Parse part.
So I started thinking that it would have been better to create a single function Get_Json and make it able to return the API request in form of object. I hit a wall and I literally have no idea how go ahead, I would really appreciate some help on how to make this correct:
using UnityEngine;
using System.Collections;
using SimpleJSON;
public class Site : MonoBehaviour {
/*
base url http://example.com/
* GET a Room: /ajax/API/?method=Get&hashtag=HASHTAG
* Create a Room: /ajax/API/?method=Create&hashtag=HASHTAG&token=TOKEN (optional)
* Delete a Room: /ajax/API/?method=Delete&hashtag=HASHTAG&token=TOKEN
* List Rooms: /ajax/API/?method=List_rooms
* List Hashtags: /ajax/API/?method=List_hashtags
*/
private string base_url = "http://example.com/ajax/API/?method=";
private string q = "";
IEnumerator Get_Json(string q){
var url = base_url+q;
WWW www = new WWW(url);
yield return www;
Debug.Log(www.text);
if (www.error == null){
var Resource = JSON.Parse(www.text);
if(int.Parse(Resource["Code"]) == 200){
Debug.Log("All right");
}
else{
Debug.Log(Resource["Code"]);
}
}
else{
Debug.Log("Failed an http request:\n"+url+"\n"+www.error);
}
yield return null;
}
// Use this for initialization
void Start () {
StartCoroutine(Get_Json("List_rooms"));
}
// Update is called once per frame
void Update () {
}
}