首页 > 解决方案 > 我需要帮助在下一行显示字符串

问题描述

我正在尝试将我的 API 的错误详细信息框到邮件正文中。在第一行我想提到 API,在下一行我需要输入错误详细信息。但是邮件正文如下所示:

WEATHER_POST is Failing and the Error details are below.. { "FaultId": "Invalid 
method type found in Request.", "fault": "FAULT_INVALID_METHOD_TYPE_IN_REQUEST" 
}BILLS_API is Failing and the Error details are below.. 
{"error":"invalid_token","error_description":"Invalid access token: 158cd00a- 
4942-4771-b54c-ed3da0f15a6c"} 

但我想看到如下消息

WEATHER_POST is Failing and the Error details are below..

{ "FaultId": "Invalid 
method type found in Request.", "fault":     "FAULT_INVALID_METHOD_TYPE_IN_REQUEST" 
}

BILLS_API is Failing and the Error details are below.. 


{"error":"invalid_token","error_description":"Invalid access token: 158cd00a- 
4942-4771-b54c-ed3da0f15a6c"} 

下面是代码,我有 api 和错误详细信息存在的 bean 列表

    StringBuffer message = new StringBuffer();
    for (MessageDetails element : failureList) {

        message.append(element.getApi()+" is Failing and the Error details are below.. ");
        message.append(element.getBody());
    }   
    JSONObject requestParams = new JSONObject();
    requestParams.put("emailBody", message.toString());

有人可以帮忙吗?

标签: java

解决方案


根据经验,我们可以尝试对您的输入字符串进行正则表达式替换。每当看到左括号或右括号时,下面的选项就会插入两个换行符。

input = input.replaceAll("(?<=\\}.)|(?=\\{)", "\n\n");

这是输出:

WEATHER_POST is Failing and the Error details are below.. 

{ "FaultId": "Invalid method type found in Request.", "fault": "FAULT_INVALID_METHOD_TYPE_IN_REQUEST}

BILLS_API is Failing and the Error details are below..

{"error":"invalid_token","error_description":"Invalid8 access token: 158cd00a- 4942-4771-b54c-ed3da0f15a6c]"} 

演示

当然,如果您可以在输入文本中包含嵌套括号,这将无法正常工作。但是,我们在您的示例数据中看不到这一点。

编辑:

上面的代码旨在全面替换您的整个消息,因此您可以将您的确切代码修改为:

String output = message.toString();
output = output.replaceAll("(?<=\\}.)|(?=\\{)", "\n\n");
JSONObject requestParams = new JSONObject();
requestParams.put("emailBody", output.toString());

推荐阅读