我有一个复杂的字符串,需要分别用分隔符“&”和“=”将其分割两次。然后我需要在Java POJO类中设置值。我需要为pojo中的requestTimestamp字段设置2020-08-11+15%3A11%3A49之类的值,在channelResponseCode中设置0036.....对于所有字段都是如此。由于每个字段的所有值都被设置。请帮忙。 我的代码如下:
public static void main(String[] args) {
String strMain = "request_timestamp=2020-08-11+15%3A11%3A49&channel_response_code=0036&channel_response_desc=Payment+is+cancelled.&sub_merchant_list=";
String arrSplit[] = strMain.split("&");
// [request_timestamp=2020-08-11+15%3A11%3A49, channel_response_code=0036, channel_response_desc=Payment+is+cancelled.,_4=, user_defined_5=, .....]
// System.out.println(Arrays.toString(arrSplit));
Payment p = new Payment();
for (String s : arrSplit) {
String[] t =s.split("=");
System.out.println(Arrays.toString(t));
if(t.length >1) {
p.setRequest_timestamp(t[1]);
}
else { p.setRequest_timestamp(""); }
System.out.println("Hiii"+p.getRequest_timestamp());
}
}
最佳答案
您可以使用 StringTokenizer 来实现此目的。
private static final String CHANEL_RESPONSE_CODE = "channel_response_code";
private static final String CHANEL_RESPONSE_DESC = "channel_response_desc";
private static final String REQUEST_TIME_STMP = "request_timestamp";
private static final String MERCHANT_LIST = "sub_merchant_list";
public static void main(String[] args) {
String strMain = "request_timestamp=2020-08-11+15%3A11%3A49&channel_response_code=0036&channel_response_desc=Payment+is+cancelled.&sub_merchant_list=";
StringTokenizer tokenizer = new StringTokenizer(strMain, "&");
while (tokenizer.hasMoreElements()){
String element = tokenizer.nextElement().toString();
if(element.contains(CHANEL_RESPONSE_CODE)){
String chanelReponseCodeValue[] = element.split("=");
if(chanelReponseCodeValue.length>=2){
System.out.println(chanelReponseCodeValue[1]);
}
}
if(element.contains(CHANEL_RESPONSE_DESC)){
String chanelReponseDescValue[] = element.split("=");
if(chanelReponseDescValue.length>=2) {
System.out.println(chanelReponseDescValue[1]);
}
}
if(element.contains(REQUEST_TIME_STMP)){
String requestTimeStmp[] = element.split("=");
if(requestTimeStmp.length>=2){
System.out.println(requestTimeStmp[1]);
}
}
if(element.contains(MERCHANT_LIST)){
String merchantList[] = element.split("=");
if(merchantList.length>=2) {
System.out.println(merchantList[1]);
}
}
}
}
关于java - 使用 Java 拆分复杂的 String 对象并将值填充到 DTO 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63449563/