0

我希望有人可以帮助我解决将数据序列化到课程中的问题吗?

我需要将以下 json 字符串发送到 Web 服务:

{ "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": "你好" }'

我将此 json 字符串放入http://json2csharp.com/并生成以下类:

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

我以前曾设法做到这一点,但从来没有遇到过班级中有班级的情况,可以这么说。意思是“Pickup”和“DropOff”设置......

当我试图弄清楚在这条线上该怎么做时,我被卡住了......

Booking bookingdetails = new ClickATaxi_Classes.Booking(THIS IS WHERE I WILL PUT THE 17 BITS OF INFORMATION BUT HOW?);

我觉得我需要对班级做一些事情以使其接受争论,但我不知道从哪里开始以及如何发送接送信息

有人可以帮忙吗?

谢谢

4

2 回答 2

2

首先,您应该稍微重构一下生成的代码

public class Location
{
     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 Booking
{
     public string arrivalAt { get; set; }
     public Location pickup { get; set; }
     public Location dropoff { get; set; }
     public string vehicleType { get; set; }
     public string comments { get; set; }
}

不需要两个具有相同含义的类。之后,您只需实例化预订对象。

Booking obj = new Booking { arrivalAt = "ARRIVAL", pickup = new Location { streetName = "", houseNumber = "" ... }, dropoff = new Location { streetName = "", houseNumber = "" ...}, vehicleType = "", comments = "" }

接下来您将序列化为一个字符串,我喜欢JSON.NET,但您可以使用任何序列化程序。
如果你想使用 JSON.NET,你可以按照这些说明通过Nuget安装它,接下来将 using 语句添加到将序列化对象的类的顶部: using Newtonsoft.Json;

最后只需调用 JsonConvert

string json = JsonConvert.SerializeObject(product);

以下是其他序列化程序的一些链接:

于 2012-11-18T17:45:55.363 回答
0

.NET . 你需要一个 JSON 序列化器。随便挑一个你喜欢的。已列出的 3 个效果很好。并确保您阅读本文以更好地理解为什么需要 JSON 序列化程序。

于 2012-11-18T17:41:28.683 回答