c# - C# 构建 Json 字符串,但我收到错误“无效的匿名类型成员声明符”
问题描述
我正在尝试创建一个这样的 Json 字符串:
{
"StreetLines": [
"101 Test St",
"Ste 100"
],
"City": "Dallas",
"StateOrProvinceCode": "TX",
"PostalCode": "75999",
"CountryCode": "US"
}
这是我的代码:
var json = new
{
StreetLines = new
{
toAddress1,
toAddress2
},
new
{
City = toCity,
StateOrProvinceCode = toState,
PostalCode = toZip,
CountryCode = toCountry
}
};
我在下部收到错误“无效的匿名类型成员声明符”。我不确定问题是什么,任何建议将不胜感激。
解决方案
首先,请注意这StreetLines
是一个 JSON 数组,因此您应该使用 C# 数组或列表:
StreetLines = new[] // notice the "[]"
{
toAddress1,
toAddress2
},
在您的 JSON 中,键City
等StateOrProvinceCode
与位于同一对象中StreetLines
,因此在您的 C# 代码中,您不应为它们创建新的匿名类。
如果 JSON 是这样的:
{
"StreetLines": [
"101 Test St",
"Ste 100"
],
"OtherPartsOfTheAddress": {
"City": "Dallas",
"StateOrProvinceCode": "TX",
"PostalCode": "75999",
"CountryCode": "US"
}
}
然后你可以写
var json = new
{
StreetLines = new[]
{
toAddress1,
toAddress2
},
OtherPartsOfTheAddress = new // notice the key name
{
City = toCity,
StateOrProvinceCode = toState,
PostalCode = toZip,
CountryCode = toCountry
}
};
但既然没有OtherPartsOfTheAddress
,你只需要这样做:
var json = new
{
StreetLines = new[]
{
toAddress1,
toAddress2
},
City = toCity,
StateOrProvinceCode = toState,
PostalCode = toZip,
CountryCode = toCountry
};
推荐阅读
- r - 创建稀疏矩阵,然后对数据进行预测分析
- reactjs - 限制输入数量
- node.js - 如何使用 connection.db.collection 函数?
- python - AppRegistryNotReady:应用程序尚未加载。使用 UserCreationForm 时
- android - 为地点选择器使用地点自动完成功能
- vb.net - VB.NET - 避免在单击“重置”按钮时执行 MsgBox
- openshift - openshift 请求经常失败
- rust - 为什么在 Rust 2018 中使用模块时出现“找不到 crate”?
- windows - 在 Windows 上安装 Chromium 时出错:断言 vc_lib_um_path
- templates - 如何在一次 Puppet 运行中使用插入的文件更新 ERB 模板?