【问题标题】:Substring continue to search until specific character子字符串继续搜索直到特定字符
【发布时间】:2017-01-10 23:26:12
【问题描述】:

我在运行时得到一个字符串。该字符串采用 JSON 格式(键值对)。其中一个键是“userId”。我需要检索userId 的值。问题是我不知道“userId”键的位置。字符串可以看起来像{"name":"XX", "userId":"YYY","age":"10"},也可以看起来像{"age":"10", "name":"XX", "userId":"YYY"},或者看起来像{"age":"10"}

我正在考虑使用substring()

var index = myString.IndexOf("userId\":\"");
if(index != -1){
  myString.Subtring(index, ???)//How to specify the length here
}

我不确定,怎么说继续,直到找到下一个"(双引号)

【问题讨论】:

  • 为什么不直接反序列化 JSON 而不是重新发明轮子?
  • 使用适当的 JSON 解析器并实际读取数据。不要尝试用字符串函数自己解析它。
  • @ErikPhilips:我想对 JSON 进行反消毒,但字符串的格式不固定。
  • 我同意其他 cmets 的观点,即尝试自己编写一个愚蠢的 JSON 解析器是荒谬的。只要做对并使用现有的工具。也就是说,您发布的一小段代码表明您知道使用string.IndexOf() 方法来查找文本"userId:"。因此,如果您知道这一点,为什么不知道使用same method 来查找文本"\""
  • @PeterDuniho:谢谢。我明白你在说什么。

标签: c# .net string linq substring


【解决方案1】:

@Wiktor Stribiżew 给出的答案也很有效。我正在粘贴他的解决方案。

System.Text.RegularExpressions.Regex.Match(myString, "\"userId\":\"([^\"]+)").Groups[1].Value

【讨论】:

    【解决方案2】:

    如果只计划使用userId 属性,您可以简单地声明一个带有userId 成员的对象并反序列化json。反序列化期间将省略任何其他属性。

    class UserIDObj
    {
       public string UserId { get; set; }
    }
    
    var obj = JsonConvert.DeserializeObject<UserIDObj>("{\"name\":\"XX\", \"userId\":\"YYY\",\"age\":\"10\"}");
    string usrID = obj.UserId;
    

    【讨论】:

      【解决方案3】:

      你可以这样做:

      var needle = "\"userId\":"; // also you forgot to escape the quote here
      var index = myString.IndexOf(needle); 
      if(index != -1){
        var afterTheUserId = myString.Substring(index + needle.Length);
        var quoteIndex = afterTheUserId.IndexOf('"');
        // do what you want with quoteIndex
      }
      

      但正如 Eric Philips 和 PhonicUK 所说,您应该使用适当的 JSON 解析器,而不是编写自己的字符串函数。

      【讨论】:

      • 我不能使用myString.Substring(index + needle.Length);。正如我所说,我不确定 JSON 输入。键的顺序和键名不固定。
      • 为什么不能使用myString.Substring(index + needle.Length);
      • @OpenStack:JSON 不要求键/值对以任何特定顺序排列。从例如维基百科:"an unordered collection of name/value pairs where the names (also called keys) are strings".
      • 我不明白为什么我的答案被否决了,我的意思是我同意这显然不是解析 OP 的 JSON 代码的好方法,但我正在回答这个问题。
      猜你喜欢
      • 2023-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-18
      • 1970-01-01
      • 2017-02-25
      • 1970-01-01
      相关资源
      最近更新 更多