[英]How to pass dictionary as part of the payload in POST request in Advanced Rest Client
I am trying to use Advanced Rest Client Chrome Extension for testing my WebApi locally and i would like to pass a dictionary as part of the payload to the POST request that i am trying to make. 我正在尝试使用Advanced Rest Client Chrome扩展程序在本地测试我的WebApi,我想将字典作为有效负载的一部分传递给我要发出的POST请求。 While debugging i found out that the dictionary even though i am passing it in json format doesn't deserialize correctly and count for Dictionary remains zero. 在调试时,我发现即使我以json格式传递字典,字典也无法正确反序列化,并且Dictionary的计数仍然为零。
Payload Example : 有效负载示例:
{
"DictionaryForEvaluationTelemetries" :{ "B":"{\"Counter\":\"500\"}"}
}
This is the simple code for the object which is part of the dictionary 这是对象的简单代码,它是字典的一部分
[DataContract]
class Class1
{
private int counter;
[DataMember]
public int Counter
{
get { return counter; }
}
public void Increment()
{
Interlocked.Increment(ref counter);
}
}
[DataContract]
public class TelemetryPayload
{
[DataMember]
public ConcurrentDictionary<string, Class1> DictionaryForEvaluationTelemetries { get; set; }
}
[HttpPost]
public void LogEvaluationTelemetry()
{
// Internally the below method does : JsonSerializer<T>.Deserialize(request.Content.ReadAsStringAsync().Result);
var telemetryPayload = Request.GetObjectFromBody<TelemetryPayload>();
}
JSON Deserialization is done by System.Runtime.Serialization.Json JSON反序列化由System.Runtime.Serialization.Json完成
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;
public static class JsonSerializer<T> where T : class
{
public static T Deserialize(string jsonObject)
{
byte[] array = Encoding.UTF8.GetBytes(jsonObject);
using (MemoryStream ms = new MemoryStream(array))
{
DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(T));
return (T)jsonSerializer.ReadObject(ms);
}
}
As far as I can tell the json you are passing doesn't have an object that will map to Class1. 据我所知,您要传递的json没有映射到Class1的对象。 Your json should look like this: 您的json应该看起来像这样:
{
"DictionaryForEvaluationTelemetries" : {"B": {"Counter": 500}}
}
where DictionaryForEvaluationTelemetries.B would map to Class1. 其中DictionaryForEvaluationTelemetries.B将映射到Class1。
Or, depending on what the Request.GetObjectFromBody<> method does, probably more like this: 或者,根据Request.GetObjectFromBody <>方法的作用,可能更像这样:
{"Counter" : 500}
There were two problems for the question asked above : 1) Payload format was incorrect : 上述问题有两个问题:1)有效载荷格式不正确:
{
"DictionaryForEvaluationTelemetries" : {"B": {"Counter": 500}}
}
2) For deserializing i was using System.Runtime.Serialization.Json. 2)对于反序列化,我正在使用System.Runtime.Serialization.Json。 I changed it to use NewtonSoft.Json JsonConvert.DeserializeObject 我将其更改为使用NewtonSoft.Json JsonConvert.DeserializeObject
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.