I was hoping someone could help me with a problem serialzing data into a class please?
I need to send the following json string to a webservice:
{ “arrivalAt”: “2012-12-24T20:00:00.0000000Z”, “pickup”:{“streetName”:”Amaliegade”,”houseNumber”:”36″,”zipCode”:”1256″,”city”:”Copenhagen K”,”country”:”DK”,”lat”:55.68,”lng”:12.59}, “dropoff”:{“streetName”:”Amaliegade”,”houseNumber”:”36″,”zipCode”:”1256″,”city”:”Copenhagen K”,”country”:”DK”,”lat”:55.68,”lng”:12.59}, “vehicleType”: “fourSeaterAny”, “comments”: “Hello” }’
I put this json string into http://json2csharp.com/ and it generated the following class:
public class Pickup
{
public string streetName { get; set; }
public string houseNumber { get; set; }
public string zipCode { get; set; }
public string city { get; set; }
public string country { get; set; }
public double lat { get; set; }
public double lng { get; set; }
}
public class Dropoff
{
public string streetName { get; set; }
public string houseNumber { get; set; }
public string zipCode { get; set; }
public string city { get; set; }
public string country { get; set; }
public double lat { get; set; }
public double lng { get; set; }
}
public class RootObject
{
public string arrivalAt { get; set; }
public Pickup pickup { get; set; }
public Dropoff dropoff { get; set; }
public string vehicleType { get; set; }
public string comments { get; set; }
}
I have managed to do this before but have never had a situation where is there is a class within a class, so to speak. Meaning the “Pickup” & “DropOff” settings…
I am stuck when i try to work out what to do at this line…
Booking bookingdetails = new ClickATaxi_Classes.Booking(THIS IS WHERE I WILL PUT THE 17 BITS OF INFORMATION BUT HOW?);
I get the feeling there is something i need to do to the class to make it accept arguments but i have no idea where to start and how to send the pickup and dropoff information
can anyone help please?
thanks
First you should refactor that generated code a little bit
There is no need for two classes that mean the same thing. After that you will just instantiate the booking object.
Next you will serialize to a string, I like JSON.NET but you can use any serializer.
If you want to use JSON.NET you can install it via Nuget by following these instructions, next add the using statement to the top of your class that will serialize the object:
using Newtonsoft.Json;
Finally just call JsonConvert
Here are some links to other serializers: