sedavidw sedavidw - 26 days ago 7
C# Question

JSON return for C# ServiceContract looks different than I'd expect

So I have a service contract that I'm using like an API with the following interface declaration

namespace MyAPI
{
[ServiceContract(Namespace = "http://MyAPI")]
public interface IMyAPI
{
[OperationContract]
[WebInvoke(Method = "GET", UriTemplate = "GetSomething?someInt={someInt}", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
Dictionary<string, List<string>> GetSomething(int someInt);
}
}


In the implementation I do something like the following

namespace MyAPI
{
[ServiceBehavior]
public class MyAPI : IMyAPI
{

public Dictionary<string, List<string>> GetSomething(int someInt)
{

Dictionary<string, List<string>> something = new Dictionary<string, List<string>>();
something["FIRST KEY"] = new List<string>();
something["SECOND KEY"] = new List<string>();

// fill up these lists...

return something;
}
}
}


However when I go to return something I get something that is formatted like this

[{"Key":"FIRST KEY","Value":[]},{"Key":"SECOND KEY","Value":[]}]


Where I would expect the JSON to look the following

{"FIRST KEY":[], "SECOND KEY":[]}


Why the difference between the two? I could serialize into a string but that just seems like an extra (unnecessary) step. Any help is greatly appreciated

Answer

It is because "something" is a container --> A list of Key value pairs. That is why you get a structure of ["key<string>": value<Array<string>>] Sorry it is just my notation.

So a dictionary translates to an array because it is collection. Its structure is to hold key value pairs that happens to be reference types. That is why you got the object notation in JSON. The value is a list of string again, that is why the array syntax.

Your expected structure describes ONE object with 2 properties like:

class SomeThing{
    [DisplayName("FIRST KEY")]
    List<string> FirstKey;

    [DisplayName("SECOND KEY")]
    List<string> SecondKey;
}
Comments