StackOverflowVeryHelpful
StackOverflowVeryHelpful

Reputation: 2427

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. 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.

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

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);
            }
}

Upvotes: 0

Views: 2955

Answers (2)

StackOverflowVeryHelpful
StackOverflowVeryHelpful

Reputation: 2427

There were two problems for the question asked above : 1) Payload format was incorrect :

{
    "DictionaryForEvaluationTelemetries" : {"B": {"Counter": 500}}
}

2) For deserializing i was using System.Runtime.Serialization.Json. I changed it to use NewtonSoft.Json JsonConvert.DeserializeObject

Upvotes: 1

Damien Jones
Damien Jones

Reputation: 66

As far as I can tell the json you are passing doesn't have an object that will map to Class1. Your json should look like this:

{
    "DictionaryForEvaluationTelemetries" : {"B": {"Counter": 500}}
}

where DictionaryForEvaluationTelemetries.B would map to Class1.

Or, depending on what the Request.GetObjectFromBody<> method does, probably more like this:

{"Counter" : 500}

Upvotes: 1

Related Questions