首页 > 解决方案 > 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
    }
};

我在下部收到错误“无效的匿名类型成员声明符”。我不确定问题是什么,任何建议将不胜感激。

标签: c#jsonlinq

解决方案


首先,请注意这StreetLines是一个 JSON 数组,因此您应该使用 C# 数组或列表:

StreetLines = new[] // notice the "[]"
{
    toAddress1,
    toAddress2
},

在您的 JSON 中,键CityStateOrProvinceCode位于同一对象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
};

推荐阅读