我有一个字符串如下,我正在拆分参数(TransactionType,ServiceID,PaymentID,OrderNumber,Amount),如下所示。
String response = "TransactionType=SALE&ServiceID=TV3&PaymentID=PYID2016061501417701&OrderNumber=2016061501417701&Amount=235.00"
String splitParams[] = res.split("&");
String TransactionType = splitParams[0].substring(splitParams[0]
.indexOf("=") + 1);
String ServiceID = splitParams[1].substring(splitParams[1]
.indexOf("=") + 1);
String PaymentID = splitParams[2].substring(splitParams[2]
.indexOf("=") + 1);
String OrderNumber = splitParams[3].substring(splitParams[3]
.indexOf("=") + 1);
String amount = splitParams[4].substring(splitParams[4]
.indexOf("=") + 1);
但问题是这些参数不按顺序发送,有时一些参数不会发送。有没有办法使用java基于参数名称拆分字符串中的参数?
答案 0 :(得分:4)
你可以像这样使用guavas Splitter:
Map<String, String> responseMap = Splitter.on("&")
.omitEmptyStrings()
.trimResults()
.withKeyValueSeparator("=")
.split(response);
然后你可以得到这样的价值:
String TransactionType = responseMp.get("TransactionType ");
答案 1 :(得分:2)
试试这个:
String response = "TransactionType=SALE&ServiceID=TV3&PaymentID=PYID2016061501417701&OrderNumber=2016061501417701&Amount=235.00";
Map<String,String> responseMap = Arrays.asList(response.split("&")).stream().
map(v-> v.split("=")).collect(Collectors.toMap(a-> a[0],a ->a[1]));
System.out.println(responseMap);
输出:
{TransactionType = SALE,金额= 235.00,PaymentID = PYID2016061501417701,OrderNumber = 2016061501417701,ServiceID = TV3}