作为一名使用VB.Net 2015社区的VB.Net程序员,我遇到了C#中需要转换为VB的项目,但这次我不明白我正在使用什么。我正在消费的网站服务返回并期望JSON / JOBJECTS结构如:
var token = new {
iss = PARTNERID,
product = "twpemp",
sub = "partner",
siteInfo = new {
type = "id",
id = SITEID
},
exp = (Int32)DateTime.UtcNow.Add(new TimeSpan(0, 4, 30)).Subtract(new DateTime(1970, 1, 1)).TotalSeconds
};
在线转换器将其转换为:
Dim EPochTime = DateTime.UtcNow.Add(New TimeSpan(0, 4, 0)).Subtract(New DateTime(1970, 1, 1)).TotalSeconds
Dim Token = New With {
Key .iss = AccNumber,
Key .product = "twppartner",
Key .sub = "partner",
Key .siteInfo = New With {
Key .type = "id",
Key .id = Site},
Key .exp = EPochTime
}
我需要动态创建这种类型的结构,因为“键名”和值会根据返回的内容而发生变化,需要发回。例如,根据上面的siteid,返回的结构可能包含以下内容:
"Results": [
{
"RecordNumber": 000001,
"EmployeeCode": "0001",
"FirstName": "John",
"MiddleName": "A",
"LastName": "Dow",
"Designation": "Worker",
"Home1": "Press",
},
{
"RecordNumber": 000002,
"EmployeeCode": "0002",
"FirstName": "Jane",
"MiddleName": "b",
"LastName": "Dow",
"Designation": "Helper",
"Home1": "Office",
}
}
对于下一个客户端,我提交了一个查询,并最终需要更新,可能有:
"Results": [
{
"RecordNumber": 12345,
"EmployeeCode": "231",
"FirstName": "Erick",
"MiddleName": "G",
"LastName": "Smith",
"Department": "Electrial",
},
{
"RecordNumber": 732456,
"EmployeeCode": "853",
"FirstName": "Fred",
"MiddleName": "W",
"LastName": "Kerber",
"Department": "Electrial",
}
}
两者之间的区别是一个有“部门”而另一个没有。此结构根据第一次调用时的siteID进行更改。
我的主要问题是如何在VB.NET中动态创建这样的东西,其次,究竟是什么类型的东西叫做?我称之为缺乏更好的词汇的结构。
答案 0 :(得分:1)
如果你想在JSON中输出这些东西有一点灵活性,有两种方法:
1)您可以使用var InputQueue = new BufferBlock<string>();
var Handler = new ActionBlock<string>(parcel =>
{
// handle parsel
});
var linkOptions = new DataflowLinkOptions { PropagateCompletion = true };
InputQueue.LinkTo(Handler, linkOptions);
// now after you call Complete method for InputQueue the completion will be propagated to your Handler block:
for (int i = 0; i < 26; i++)
{
await InputQueue.SendAsync(((char)(97 + i)).ToString());
}
InputQueue.Complete();
await Handler.Completion;
代替动态类型。使用字典方法,您可以在运行时添加(或排除)属性。 JSON序列化程序将以与序列化动态类型相同的方式输出。
Dictionary<string,object>
2)您可以创建一个具有JSON结构可能包含的所有可用属性的类。对于数字类型的可选属性,请将它们设为可为空:
var dict = new Dictionary<string, object>() { { "key1", "value1"} };
dict["key2"] = DateTime.Now();
dict["key3"] = 1234567;
if (someCondition){
dict["key4"] = new Dictionary<string, object>() { { "key5", "value5"}, { "key6", "value6"}};
}
上述课程可能适用于您提供的两种情景。未指定值的属性将在JSON中序列化为public class Qwijibo
{
public int? RecordNumber {get;set;}
public string EmployeeCode {get;set;}
public string FirstName {get;set;}
public string MiddleName {get;set;}
public string LastName {get;set;}
public string Designation {get;set;}
public string Home1 {get;set;}
public string Department {get;set;
}
。只要您传输的内容不会挂在null
值上,您就可以开始了。