分割一个复杂的String对象,并使用Java将值填充到DTO中

huangapple go评论71阅读模式
英文:

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]

注意:

  1. 您可以在这里了解更多关于URL解码的信息(取自Homilzio的回答)
  2. 您可以探索ObjectMapper以进行更精细的转换。
英文:

Here is a Java8 with Jackson library way of doing it:

Payment Class:

public class Payment {
    
    // You don&#39;t need @JsonProperty annotation if you have param name 
    // &quot;requestTimestamp&quot; in your URL or if you name the attribute here in POJO 
    // as &quot;request_timestamp&quot;

	@JsonProperty(&quot;request_timestamp&quot;)
	String requestTimestamp;
	
	@JsonProperty(&quot;channel_response_code&quot;)
	String channelResponseCode;
	
	@JsonProperty(&quot;channel_response_desc&quot;)
	String channelResponseDesc;
	
	@JsonProperty(&quot;sub_merchant_list&quot;)
	String subMerchantList;

	// getters and setters
}
public class Test {
	public static void main(String[] args) throws UnsupportedEncodingException {
		String strMain = &quot;request_timestamp=2020-08-11+15%3A11%3A49&amp;channel_response_code=0036&amp;channel_response_desc=Payment+is+cancelled.&amp;sub_merchant_list=1&quot;;

		Map&lt;String, String&gt; map = 
				Arrays.stream(URLDecoder.decode(strMain, &quot;UTF-8&quot;).split(&quot;&amp;&quot;))
				.collect(
						Collectors.toMap(
								k -&gt; ((String) k).split(&quot;=&quot;)[0], 
								v -&gt; ((String) v).split(&quot;=&quot;)[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:

  1. You can explore more about URL decoding here (taken from Homilzio's answer)
  2. 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(&quot;&amp;&quot;);
for (int i = 0; i &lt; arrSplit.length; i++) {
String[] keyValue = arrSplit[i].split(&quot;=&quot;);
String key = null;
if (keyValue.length &gt; 0) {
key = keyValue[0];
}
String value = null;
if (keyValue.length &gt; 1) {
value = keyValue[1];
}
this.setPropertyValue(key, value);
}
}
private void setPropertyValue(String key, String value) {
System.out.println(String.format(&quot;&#39;%s&#39; = &#39;%s&#39;&quot;, key, value));
switch (key) {
case &quot;request_timestamp&quot;:
this.requestTimestamp = value;
return;
case &quot;channel_response_code&quot;:
this.channelResponseCode = value;
return;
case &quot;channel_response_desc&quot;:
this.channelResponseDesc = value;
return;
case &quot;sub_merchant_list&quot;:
this.subMerchantList = value;
return;
default:
throw new RuntimeException(String.format(&quot;Invalid key &#39;%s&#39;&quot;, key));
}
}
@Override
public String toString() {
return &quot;Payment{&quot; +
&quot;requestTimestamp=&#39;&quot; + requestTimestamp + &#39;\&#39;&#39; +
&quot;, channelResponseCode=&#39;&quot; + channelResponseCode + &#39;\&#39;&#39; +
&quot;, channelResponseDesc=&#39;&quot; + channelResponseDesc + &#39;\&#39;&#39; +
&quot;, subMerchantList=&#39;&quot; + subMerchantList + &#39;\&#39;&#39; +
&#39;}&#39;;
}
}
@Test
void stackOverflow() {
String strMain = &quot;request_timestamp=2020-08-11+15%3A11%3A49&amp;channel_response_code=0036&amp;channel_response_desc=Payment+is+cancelled.&amp;sub_merchant_list=&quot;;
Payment payment = Payment.parsePayment(strMain);
System.out.println(payment.toString());
}

The result:

&#39;request_timestamp&#39; = &#39;2020-08-11+15%3A11%3A49&#39;
&#39;channel_response_code&#39; = &#39;0036&#39;
&#39;channel_response_desc&#39; = &#39;Payment+is+cancelled.&#39;
&#39;sub_merchant_list&#39; = &#39;null&#39;
Payment{requestTimestamp=&#39;2020-08-11+15%3A11%3A49&#39;, channelResponseCode=&#39;0036&#39;, channelResponseDesc=&#39;Payment+is+cancelled.&#39;, subMerchantList=&#39;null&#39;}

huangapple
  • 本文由 发表于 2020年8月17日 19:02:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/63449563.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定