【问题标题】:Append text in json response在 json 响应中附加文本
【发布时间】:2016-12-23 22:22:17
【问题描述】:

我在变量 responseString 中收到以下 JSON 格式的消息

{
  "CreateCustomerResponse": {
    "ServiceContextType": {
      "Status": {
        "Code": "EI7",
        "MessageType": "ERROR",
        "Message": "Email Oops! Looks like you've already created an account. Please <a href='/account'>click here to sign in.</a>"
      }
    }
  }
}

我想用https://www.myweb.com/signin/ 替换收到的href 值。有可能吗?

 string responseString = client.POST(relativeURL, createCustomerRequest, contentType);
 responseString = //Replace /account with `https://www.myweb.com/signin/`

【问题讨论】:

  • 是的,这是可能的。使用正则表达式进行模式匹配可能是最简单的。您可能想先反序列化 JSON 字符串,或者这可能无关紧要。
  • 我认为最可靠的方法是将字符串反序列化为对象,将对象的属性修改为您想要的。
  • @YonF 建议指出。谢谢

标签: c# json append


【解决方案1】:

您可以使用字符串函数 replace()、replaceAll() 等。 像这样:

String responseString = client.POST(relativeURL, createCustomerRequest, contentType);
String responseStringReplaced=responseString.replace("/account","https://www.myweb.com/signin/");

【讨论】:

    【解决方案2】:

    你可以像这样使用正则表达式:

    string responseString = client.POST(relativeURL, createCustomerRequest, contentType);
    string replace = "https://www.myweb.com/signin/";
    
    string result = Regex.Replace(responseString, @"href='(.*?)'", $"href='{replace}'");
    
    // => ...href='https://www.myweb.com/signin/'>click here to sign in.</a>...
    

    【讨论】:

      猜你喜欢
      • 2018-09-10
      • 2019-06-21
      • 2021-05-05
      • 2013-08-28
      • 1970-01-01
      • 1970-01-01
      • 2019-04-30
      • 2014-01-04
      • 1970-01-01
      相关资源
      最近更新 更多