如何从列表

时间:2016-07-18 13:55:35

标签: c# arrays string

我有一个返回字符串列表的函数

static List<string> getPushIDsForCategory(string user, string project)
{
    ....
}

然后即时使用该函数即时构建一个json字符串

  var JSON = "{\"app_id\": \"MY_ID_KEY\"," +
          "\"contents\": {\"en\": \"My Message\"}," +
          "\"ios_badgeType\": \"Increase\"," +
          "\"ios_badgeCount\": \"1\"," +
          "\"include_player_ids\": [\"" + getPushIDsForCategory(user, project) + "\"]" + //<-- that string array goes here (item 1, item 2, item 3, etc...)
          "}";

当我运行此代码时,我得到了

{
  ...
  "include_player_ids": ["System.Collections.Generic.List 1[System.String]"]
  ...
}

如果我将其替换为getPushIDsForCategory(user, project)).ToArray

我得到了

{
  ...
    "include_player_ids": ["System.String[]"]
  ...
}

我如何获得实际字符串而不是对象类型?

2 个答案:

答案 0 :(得分:3)

我相信你要找的是string.Join(", ", getPushIDsForCategory(user, project));

这将获取数组中的每个对象,并使用", "(逗号空间)的分隔符将它们连接在一起

正如其他提到的那样,这将引起后来的头痛。

看看http://www.newtonsoft.com/json

答案 1 :(得分:0)

的变化:

static string[] getPushIDsForCategory(string user, string project)

var idsArray = String.Join(", ", getPushIDsForCategory(user, project));
"\"include_player_ids\": [\"" + idsArray + "\"]"

那就是说,你可能不想像那样创建Json。你在那里建造的东西叫做“神奇的绳子”。这意味着如果你的Json有问题,你会发现在运行时而不是编译时。相反,有一个类映射所有数据并使用它来创建Json。