I would like to send a json request to a flask server. I use UnityWebRequest
to do so as following,
IEnumerator Post(string url, string bodyJsonString)
{
var request = new UnityWebRequest(url, "POST");
byte[] bodyRaw = Encoding.UTF8.GetBytes(bodyJsonString);
request.uploadHandler = (UploadHandler) new UploadHandlerRaw(bodyRaw);
request.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer();
request.SetRequestHeader("Content-Type", "application/json");
yield return request.SendWebRequest();
}
I use the following code to create the json,
Dictionary<string, string> RootJson = new Dictionary<string, string>();
Dictionary<string, float> id_val = new Dictionary<string, float>();
Dictionary<string,byte[]> employeeData = new Dictionary<string, byte[]>();
CalibrationJson.Add("id",1);
imagesJson.Add("employeeData",encodedByte);
RootJson.Add("id", JsonConvert.SerializeObject(id_val.ToString()));
RootJson.Add("data", JsonConvert.SerializeObject(employeeData.ToString()));
StartCoroutine(Post("http://127.0.0.1:5000/emp_detail", JsonConvert.SerializeObject(RootJson.ToString())));
However it is not creating a proper json though I have serialized the dictionary everytime. It throws the following error in the server,
System.Collections.Generic.Dictionary`2[System.String,System.String]
What am I missing?
Remove ToString
from your serialization code:
RootJson.Add("id", JsonConvert.SerializeObject(id_val));
RootJson.Add("data", JsonConvert.SerializeObject(employeeData));
StartCoroutine(Post("http://127.0.0.1:5000/emp_detail", JsonConvert.SerializeObject(RootJson)));
For types which do not override ToString
it will return the type name, so for Dictionary<string, string>()
you will get "System.Collections.Generic.Dictionary`2[System.String,System.String]":
Console.WriteLine(new Dictionary<string, string>().ToString()); // prints System.Collections.Generic.Dictionary`2[System.String,System.String]