How to return a dictionary of user-type values ​​as a regular JSON object from a WCF REST method?

Let's say I have a custom type that looks like this:

[DataContract]
public class CompositeType
{
    [DataMember]
    public bool HasPaid
    {
        get;
        set;
    }

    [DataMember]
    public string Owner
    {
        get;
        set;
    }
}

and the WCF REST interface, which looks like this:

[ServiceContract]
public interface IService1
{
    [OperationContract]
    Dictionary<string, CompositeType> GetDict();
}

then how do I get my implementation of this method to return a JSON object that looks like this ...

{"fred":{"HasPaid":false,"Owner":"Fred Millhouse"},"joe":{"HasPaid":false,"Owner":"Joe McWirter"},"bob":{"HasPaid":true,"Owner":"Bob Smith"}}

I do not want this to look like this:

[{"Key":"fred","Value":{"HasPaid":false,"Owner":"Fred Millhouse"}},{"Key":"joe","Value":{"HasPaid":false,"Owner":"Joe McWirter"}},{"Key":"bob","Value":{"HasPaid":true,"Owner":"Bob Smith"}}]

Ideally, I would prefer not to change the type of the returned method.

I tried many different approaches, but I can not find a solution that works. Annoyingly, it is easy to create a JSON object structure in the right form on a single line with Newtonsoft.Json:

string json = JsonConvert.SerializeObject(dict);

where is dictdefined as:

Dictionary<string, CompositeType> dict = new Dictionary<string, CompositeType>();
dict.Add("fred", new CompositeType { HasPaid = false, Owner = "Fred Millhouse" });
dict.Add("joe", new CompositeType { HasPaid = false, Owner = "Joe McWirter" });
dict.Add("bob", new CompositeType { HasPaid = true, Owner = "Bob Smith" });

WCF. , ; , WCF , , REST.

+4
1

@dbc. JSON ...

{"fred":{"HasPaid":false,"Owner":"Fred Millhouse"},"joe":{"HasPaid":false,"Owner":"Joe McWirter"},"bob":{"HasPaid":true,"Owner":"Bob Smith"}}

, , Message. :

[ServiceContract]
public interface IService1
{
    [OperationContract]
    Message GetDict();
}

:

using Newtonsoft.Json;
...
[WebGet(ResponseFormat = WebMessageFormat.Json)]
public Message GetDict()
{
    Dictionary<string, CompositeType> dict = new Dictionary<string, CompositeType>();
    dict.Add("fred", new CompositeType { HasPaid = false, Owner = "Fred Millhouse" });
    dict.Add("joe", new CompositeType { HasPaid = false, Owner = "Joe McWirter" });
    dict.Add("bob", new CompositeType { HasPaid = true, Owner = "Bob Smith" });

    string json = JsonConvert.SerializeObject(dict);
    return WebOperationContext.Current.CreateTextResponse(json, "application/json; charset=utf-8", Encoding.UTF8);
}

, , Stream, JSON - URI REST.

+3

Source: https://habr.com/ru/post/1629433/


All Articles