Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WCF - How to serialize and deserialize in JSON?

I have written few classes (Data contracts and Service contracts) in WCF and i'm trying to serialize and deserialize in JSON. If i need the following JSON structure, how would i create the DataContract(s):

{
  "response": {
    "locations": {
      "location": [
        {
          "id": "12",
          "name": "Hello",
          "statusid": "78"
        },
        {
          "id": "5",
          "name": "Ann",
          "statusid": "8"
        }
      ]
    },
    "error": "404 error"
  }
}

The structure above is pretty straight forward and under locations there can be several location details as mentioned above. So i need to get an array/list to "locations" data members as mentioned below. At the moment i have the following DataContract only:

[DataContract]
    public class Response
    {
        [DataMember]
        public string locations { get; set; }

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

Please let me know how i can resolve this?

like image 586
Pavan Welihinda Avatar asked Mar 13 '13 17:03

Pavan Welihinda


2 Answers

The full objects you are looking for should be structured as:

[DataContract(Name="response")]
public class Response
{
    [DataMember(Name = "locations")]
    public IEnumerable<Location> Locations { get; set; }

    [DataMember(Name = "error")]
    public string Error { get; set; }
}

[DataContract(Name = "location")]
public class Location
{
    [DataMember(Name = "id")]
    public string Id { get; set; }

    [DataMember(Name = "name")]
    public string Name { get; set; }

    [DataMember(Name = "statusid")]
    public string StatusId { get; set; }
}

You need to setup the object hierarchy, as indicated by the { and }, as well as the IEnumerable / array properties, as indicated by the [ and ] from your desired JSON output.

The site can be confusing, as there are no simple examples, but please review Introducing JSON for a basic understanding of the syntax. Another good site I came along, with just some simple examples, was JSON and XML Serialization in ASP.NET Web API.

Thanks to some guidance by vittore, I noticed that to build the exact match to your JSON output, you will need objects like:

[DataContract]
public class ResponseParent
{
    [DataMember(Name = "response")]
    public Response ResponseInstance { get; set; }
}

[DataContract]
public class Response
{
    [DataMember(Name = "locations")]
    public LocationCollectionIntermediate Locations { get; set; }

    [DataMember(Name = "error")]
    public string Error { get; set; }
}

[DataContract]
public class LocationCollectionIntermediate
{
    [DataMember(Name = "location")]
    public IEnumerable<Location> Locations { get; set; }
}

[DataContract]
public class Location
{
    [DataMember(Name = "id")]
    public string Id { get; set; }

    [DataMember(Name = "name")]
    public string Name { get; set; }

    [DataMember(Name = "statusid")]
    public string StatusId { get; set; }
}

I've added these into a second code block here, because such a structure seems needlessly complicated. However, if you are in a position where you can change the expected output of your JSON, I'd go with the first block, with the additional change of making the two Id columns into int types.

These types were created to support a service similar to as setup at WCF Service to return JSON, and tested using the following code:

string json;
using (var ms = new MemoryStream())
{
    var ser = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(ResponseParent));
    ser.WriteObject(ms, r);
    json = System.Text.Encoding.UTF8.GetString(ms.GetBuffer(), 0, Convert.ToInt32(ms.Length)); 
}

Details on DataContractJsonSerializer

Note also that if you have the option to setup a RESTful web service, then you can follow the guidelines of How to create a JSON WCF RESTful Service in 60 seconds.

like image 166
Mike Guthrie Avatar answered Sep 22 '22 13:09

Mike Guthrie


Visit http://json.codeplex.com/. Use

JsonConvert.SerializeObject()

to turn your object into a JSON string. Use

JsonConvert.PopulateObject

to turn JSON string into an object.

like image 43
lcryder Avatar answered Sep 24 '22 13:09

lcryder