- Home /
How to Pass a Json as Post Data to WWWForm
Hi, I have been searching for a solution for this,but unable to find a perfect solutions for this. Please let me know how to pass a JSON String as Post Data to the WWWForm ?
Answer by Majorana · Jul 11, 2015 at 12:17 PM
Hi,
You have to create a Dictionary and call an other constructor of WWW class. To get your json (i use miniJson library, you can find many json parser for C# on internet) value :
var dict = Json.Deserialize(get_data) as IDictionary;
Dictionary<string,string> postParam = new Dictionary<string, string>();
postParam.Add ("param", "value");
Example :
WWWForm form = new WWWForm();
foreach(KeyValuePair<String,String> post_arg in post)
{
form.AddField(post_arg.Key, post_arg.Value);
Debug.Log(post_arg.Key);
}
WWW www = new WWW(url, form);
Answer by kmfjsc · Nov 30, 2016 at 07:59 AM
I've done for doing this below. Let's go : ==>
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
public class btnGetData : MonoBehaviour {
void Start()
{
gameObject.GetComponent<Button>().onClick.AddListener(TaskOnClick);
}
IEnumerator WaitForWWW(WWW www)
{
yield return www;
string txt = "";
if (string.IsNullOrEmpty(www.error))
txt = www.text; //text of success
else
txt = www.error; //error
GameObject.Find("Txtdemo").GetComponent<Text>().text = "++++++\n\n" + txt;
}
void TaskOnClick()
{
try
{
GameObject.Find("Txtdemo").GetComponent<Text>().text = "starting..";
string ourPostData = "{\"plan\":\"TESTA02\"";
Dictionary<string,string> headers = new Dictionary<string, string>();
headers.Add("Content-Type", "application/json");
//byte[] b = System.Text.Encoding.UTF8.GetBytes();
byte[] pData = System.Text.Encoding.ASCII.GetBytes(ourPostData.ToCharArray());
///POST by IIS hosting...
WWW api = new WWW("http://192.168.1.120/si_aoi/api/total", pData, headers);
///GET by IIS hosting...
///WWW api = new WWW("http://192.168.1.120/si_aoi/api/total?dynamix={\"plan\":\"TESTA02\"");
StartCoroutine(WaitForWWW(api));
}
catch (UnityException ex) { Debug.Log(ex.Message); }
}
}
Your answer
Follow this Question
Related Questions
Calling Json script and displaying the Images within the script 0 Answers
Footprint of System.Web on a project 0 Answers
POST request using WWW class. error: necessary data rewind wasn't possible 2 Answers
WWWForm always returning Internal Server Error 1 Answer
Would a WWW to a PHP file return the computers Info? 0 Answers