简体   繁体   English

从字典中正确将字符串转换为 Json

[英]Converting String to Json Properly from the Dictionary

I would like to send a json request to a flask server.我想向 flask 服务器发送 json 请求。 I use UnityWebRequest to do so as following,我使用UnityWebRequest执行以下操作,

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,我使用以下代码创建 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.但是,尽管我每次都对字典进行序列化,但它并没有创建正确的 json。 It throws the following error in the server,它在服务器中引发以下错误,

System.Collections.Generic.Dictionary`2[System.String,System.String] System.Collections.Generic.Dictionary`2[System.String,System.String]

What am I missing?我错过了什么?

Remove ToString from your serialization code:从序列化代码中删除ToString

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]" :对于不覆盖ToString的类型,它将返回类型名称,因此对于Dictionary<string, string>()您将获得"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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM