Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Count Query in Unity
using UnityEngine;
using System.Collections;
using System.Net;
using System.IO;
using JsonOrg;

public class NewBehaviourScript : MonoBehaviour {

	private string message = "";
	private WWW www = null;
	// Note: URL should be changed depending on your application attributes.
	// host : api.kii.com (us) / api-cn2.kii.com (china)
	// appid : 6b7bb410 -> {your application id}
	private const string bucketUrl = "http://api-jp.kii.com/api/apps/6b7bb410/buckets/myBucket/query";
	private const string queryStr = 
	"{" +
		"\"bucketQuery\" : {" +
		"\"clause\" : {" +
		"\"type\" : \"all\"" +
		"}," +
		"\"aggregations\" : [{" +
			"\"type\" : \"COUNT\"," +
			"\"putAggregationInto\" : \"count_field\"" +
			"}]" +
		"}" +
	"}";

	void Start () {
		WWWForm form = new WWWForm();
		Hashtable headers = form.headers;
		// Should be replaced with your app-id
		headers["x-kii-appid"] = "6b7bb410";
		// Should be replaced with your app-key
		headers["x-kii-appkey"] = "8e6556808410b4d05d72b407de4a31ac";
		headers["Content-Type"] = "application/vnd.kii.queryrequest+json";
		byte[] b = System.Text.Encoding.UTF8.GetBytes(queryStr);
		www = new WWW(bucketUrl, b, headers);
	}

	// Update is called once per frame
	void Update () {
	}

	void OnGUI() {
		if (www.isDone)
		{
			string resp = www.text;
			try {
				JsonObject obj = new JsonObject(resp);
				JsonObject ags = obj.GetJsonObject("aggregations");
				int count = ags.GetInt ("count_field");
				message = string.Format("objects in bucket: {0}", count);
			}
			catch (JsonException e) {
				Debug.LogError(e.Message);
			}
		}
		GUI.Box (new Rect(100,25, 200,100), message);
	}

}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.