我必须创建一个JSON字符串,最后应该如下所示:
{
"PersonId": "abc",
"Firstname": "Max",
"Lastname": "Muster",
"AddressLine1": "Hauptstrasse 3",
"ZipCode": "8000",
"City": "Zürich",
"ClubRelatedPersonDetails":
{
"IsGliderInstructor": true,
"IsGliderTrainee": false,
"IsTowPilot": true,
}
}
我已经有两个单独的JObjects
:
- 一个名为
pers
,其中包含所有名称和地址信息(在上面的示例中PersonId
到City
) - 另一个称为
clubPers
,其中包含与俱乐部相关的信息(IsGliderInstructor
到IsTowPilot
)
所以我必须添加clubPers
作为pers
的JObject
,我想? 如何在 VB.NET 中执行此操作?
只需在第一个JObject
上使用 Add
方法,提供所需的属性名称和其他JObject
作为参数。
例如:
Dim json1 As String = _
"{" + _
" ""PersonId"": ""abc""," + _
" ""Firstname"": ""Max""," + _
" ""Lastname"": ""Muster""," + _
" ""AddressLine1"": ""Hauptstrasse 3""," + _
" ""ZipCode"": ""8000""," + _
" ""City"": ""Zürich""" + _
"}"
Dim json2 As String = _
"{" + _
" ""IsGliderInstructor"": true," + _
" ""IsGliderTrainee"": false," + _
" ""IsTowPilot"": true" + _
"}"
Dim pers As JObject = JObject.Parse(json1)
Dim clubPers As JObject = JObject.Parse(json2)
pers.Add("ClubRelatedPersonDetails", clubPers)
Console.WriteLine(pers.ToString())
输出:
{
"PersonId": "abc",
"Firstname": "Max",
"Lastname": "Muster",
"AddressLine1": "Hauptstrasse 3",
"ZipCode": "8000",
"City": "Zürich",
"ClubRelatedPersonDetails": {
"IsGliderInstructor": true,
"IsGliderTrainee": false,
"IsTowPilot": true
}
}
如果"选项严格"和"选项显式"处于关闭状态:
Dim pers = JObject.Parse(json1)
Dim clubPers = JObject.Parse(json2)
pers.ClubRelatedPersonDetails = clubPers
Console.WriteLine(pers.ToString())
如果他们打开,那么使用布莱恩罗杰斯的答案。
奖励:在 C# 中,我们编写,
dynamic pers = JObject.Parse(json1);
dynamic clubPers = JObject.Parse(json2);
pers.ClubRelatedPersonDetails = clubPers;