英文:
Split a complex String object and populate values into DTO using Java
问题
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("&");
Payment p = new Payment();
for (String s : arrSplit) {
String[] t = s.split("=");
if (t.length > 1) {
if (t[0].equals("request_timestamp")) {
p.setRequestTimestamp(t[1]);
} else if (t[0].equals("channel_response_code")) {
p.setChannelResponseCode(t[1]);
} else if (t[0].equals("channel_response_desc")) {
p.setChannelResponseDesc(t[1]);
} // Add similar cases for other fields
System.out.println("Hiii" + p.getRequestTimestamp());
}
}
}
class Payment {
private String requestTimestamp;
private String channelResponseCode;
private String channelResponseDesc;
// Add other fields and their setter methods
public void setRequestTimestamp(String requestTimestamp) {
this.requestTimestamp = requestTimestamp;
}
public void setChannelResponseCode(String channelResponseCode) {
this.channelResponseCode = channelResponseCode;
}
public void setChannelResponseDesc(String channelResponseDesc) {
this.channelResponseDesc = channelResponseDesc;
}
// Add other setter methods
}
英文:
I have a complex string which I need to split two times by delimiters '&' and '=' respectively. Then I need to set the values in Java POJO class.I need values like 2020-08-11+15%3A11%3A49 to be set for requestTimestamp field in pojo, 0036 in channelResponseCode..... Like this for all fields. Due to for each all values are getting set for one field. Please help.
My code as follows:
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());
}
}
答案1
得分: 2
你可以使用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]);
}
}
}
}
英文:
You can use StringTokenizer for that purpose.
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]);
}
}
}
}
答案2
得分: 1
以下是使用Java 8和Jackson库的示例代码:
Payment
类:
public class Payment {
// 如果在URL中有参数名“requestTimestamp”,或者在POJO中将属性命名为“request_timestamp”,则不需要@JsonProperty注解
@JsonProperty("request_timestamp")
String requestTimestamp;
@JsonProperty("channel_response_code")
String channelResponseCode;
@JsonProperty("channel_response_desc")
String channelResponseDesc;
@JsonProperty("sub_merchant_list")
String subMerchantList;
// 获取器和设置器
}
public class Test {
public static void main(String[] args) throws UnsupportedEncodingException {
String strMain = "request_timestamp=2020-08-11+15%3A11%3A49&channel_response_code=0036&channel_response_desc=Payment+is+cancelled.&sub_merchant_list=1";
Map<String, String> map =
Arrays.stream(URLDecoder.decode(strMain, "UTF-8").split("&"))
.collect(
Collectors.toMap(
k -> ((String) k).split("=")[0],
v -> ((String) v).split("=")[1]) // 注意ArrayIndexOutOfBoundException
);
// 使用Jackson库: import com.fasterxml.jackson.databind.ObjectMapper;
ObjectMapper mapper = new ObjectMapper();
Payment pojo = mapper.convertValue(map, Payment.class);
System.out.println(pojo.toString());
}
}
输出:
Payment [requestTimestamp=2020-08-11 15:11:49, channelResponseCode=0036, channelResponseDesc=Payment is cancelled., subMerchantList=1]
注意:
- 您可以在这里了解更多关于URL解码的信息(取自Homilzio的回答)
- 您可以探索
ObjectMapper
以进行更精细的转换。
英文:
Here is a Java8 with Jackson library way of doing it:
Payment
Class:
public class Payment {
// You don't need @JsonProperty annotation if you have param name
// "requestTimestamp" in your URL or if you name the attribute here in POJO
// as "request_timestamp"
@JsonProperty("request_timestamp")
String requestTimestamp;
@JsonProperty("channel_response_code")
String channelResponseCode;
@JsonProperty("channel_response_desc")
String channelResponseDesc;
@JsonProperty("sub_merchant_list")
String subMerchantList;
// getters and setters
}
public class Test {
public static void main(String[] args) throws UnsupportedEncodingException {
String strMain = "request_timestamp=2020-08-11+15%3A11%3A49&channel_response_code=0036&channel_response_desc=Payment+is+cancelled.&sub_merchant_list=1";
Map<String, String> map =
Arrays.stream(URLDecoder.decode(strMain, "UTF-8").split("&"))
.collect(
Collectors.toMap(
k -> ((String) k).split("=")[0],
v -> ((String) v).split("=")[1]) // watch out for ArrayIndexOutOfBoundException
);
// using Jackson library: import com.fasterxml.jackson.databind.ObjectMapper;
ObjectMapper mapper = new ObjectMapper();
Payment pojo = mapper.convertValue(map, Payment.class);
System.out.println(pojo.toString());
}
}
Output:
Payment [requestTimestamp=2020-08-11 15:11:49, channelResponseCode=0036, channelResponseDesc=Payment is cancelled., subMerchantList=1]
Note:
- You can explore more about URL decoding here (taken from Homilzio's answer)
- You can exlpore
ObjectMapper
for more fine grained conversion.
答案3
得分: 0
似乎您在处理编码方面遇到了问题,您可以尝试:
URLEncoder.encode(strMain, StandardCharsets.UTF_8);
之前的代码。
有关类似问题的更多信息可在此处找到:这里
英文:
It seems that you are having issues with encoding, you can try:
URLEncoder.encode(strMain, StandardCharsets.UTF_8);
beefore.
More info in a similar question here
答案4
得分: 0
class Payment {
String requestTimestamp;
String channelResponseCode;
String channelResponseDesc;
String subMerchantList;
public static Payment parsePayment(String input) {
return new Payment(input);
}
private Payment(String input) {
String arrSplit[] = input.split("&");
for (int i = 0; i < arrSplit.length; i++) {
String[] keyValue = arrSplit[i].split("=");
String key = null;
if (keyValue.length > 0) {
key = keyValue[0];
}
String value = null;
if (keyValue.length > 1) {
value = keyValue[1];
}
this.setPropertyValue(key, value);
}
}
private void setPropertyValue(String key, String value) {
System.out.println(String.format("'%s' = '%s'", key, value));
switch (key) {
case "request_timestamp":
this.requestTimestamp = value;
return;
case "channel_response_code":
this.channelResponseCode = value;
return;
case "channel_response_desc":
this.channelResponseDesc = value;
return;
case "sub_merchant_list":
this.subMerchantList = value;
return;
default:
throw new RuntimeException(String.format("Invalid key '%s'", key));
}
}
@Override
public String toString() {
return "Payment{" +
"requestTimestamp='" + requestTimestamp + '\'' +
", channelResponseCode='" + channelResponseCode + '\'' +
", channelResponseDesc='" + channelResponseDesc + '\'' +
", subMerchantList='" + subMerchantList + '\'' +
'}';
}
}
@Test
void stackOverflow() {
String strMain = "request_timestamp=2020-08-11+15%3A11%3A49&channel_response_code=0036&channel_response_desc=Payment+is+cancelled.&sub_merchant_list=";
Payment payment = Payment.parsePayment(strMain);
System.out.println(payment.toString());
}
结果:
'request_timestamp' = '2020-08-11+15%3A11%3A49'
'channel_response_code' = '0036'
'channel_response_desc' = 'Payment+is+cancelled.'
'sub_merchant_list' = 'null'
Payment{requestTimestamp='2020-08-11+15%3A11%3A49', channelResponseCode='0036', channelResponseDesc='Payment+is+cancelled.', subMerchantList='null'}
英文:
What about something like this?
class Payment {
String requestTimestamp;
String channelResponseCode;
String channelResponseDesc;
String subMerchantList;
public static Payment parsePayment(String input) {
return new Payment(input);
}
private Payment(String input) {
String arrSplit[] = input.split("&");
for (int i = 0; i < arrSplit.length; i++) {
String[] keyValue = arrSplit[i].split("=");
String key = null;
if (keyValue.length > 0) {
key = keyValue[0];
}
String value = null;
if (keyValue.length > 1) {
value = keyValue[1];
}
this.setPropertyValue(key, value);
}
}
private void setPropertyValue(String key, String value) {
System.out.println(String.format("'%s' = '%s'", key, value));
switch (key) {
case "request_timestamp":
this.requestTimestamp = value;
return;
case "channel_response_code":
this.channelResponseCode = value;
return;
case "channel_response_desc":
this.channelResponseDesc = value;
return;
case "sub_merchant_list":
this.subMerchantList = value;
return;
default:
throw new RuntimeException(String.format("Invalid key '%s'", key));
}
}
@Override
public String toString() {
return "Payment{" +
"requestTimestamp='" + requestTimestamp + '\'' +
", channelResponseCode='" + channelResponseCode + '\'' +
", channelResponseDesc='" + channelResponseDesc + '\'' +
", subMerchantList='" + subMerchantList + '\'' +
'}';
}
}
@Test
void stackOverflow() {
String strMain = "request_timestamp=2020-08-11+15%3A11%3A49&channel_response_code=0036&channel_response_desc=Payment+is+cancelled.&sub_merchant_list=";
Payment payment = Payment.parsePayment(strMain);
System.out.println(payment.toString());
}
The result:
'request_timestamp' = '2020-08-11+15%3A11%3A49'
'channel_response_code' = '0036'
'channel_response_desc' = 'Payment+is+cancelled.'
'sub_merchant_list' = 'null'
Payment{requestTimestamp='2020-08-11+15%3A11%3A49', channelResponseCode='0036', channelResponseDesc='Payment+is+cancelled.', subMerchantList='null'}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论