Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind a string to object in java

I have a string in this format(response from EBS Payment Gateway)

key1=value1&key2=value2&key3=value3

How to bind to this class object without using split method?

public class MyClass {

    private String key1;
    private String key2;
    private String key3;
    // getter and setter methods
    ...
}
like image 319
vivek Avatar asked Jul 09 '13 11:07

vivek


2 Answers

Try following

public class MyClass {

    private String key1;
    private String key2;
    private String key2;

    public MyClass(String k1,String k2,String k3)
    {
        Key1 = k1;
        Key2 = k2;
        Key3 = k3;
    }
// getter and setter methods
...
}

And while creating object of class

String response = "key1=value1&key2=value2&key3=value3";
String[] keys = response.split("&");
MyClass m = new MyClass(keys[0].split("=")[1],keys[1].split("=")[1],keys[2].split("=")[1])
like image 83
W A K A L E Y Avatar answered Nov 02 '22 07:11

W A K A L E Y


String template = "key1=value1&key2=value2&key3=value3";
String pattern = "&?([^&]+)="; 

Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(template);

while (m.find()) 
{
    System.out.println(m.group(1)); //prints capture group number 1
}

Output:

   key1
   key2  
   key3

Of course, this can be shortened to:

Matcher m = Pattern.compile("&?([^&]+)=").matcher("key1=value1&key2=value2&key3=value3");

while (m.find()) 
{
    System.out.println(m.group(1)); //prints capture group number 1
}

Breakdown:

"&?([^&]+)="; 

&?: says 0 or 1 &
[^&]+ matches 1 or more characters not equal to &
([^&]+) captures the above characters (allows you to extract them)
&?([^&]+)= captures the above characters such that they begin with 0 or 1 & and end with =

NB: Even though we did not exclude = in [^&], this expression works because if it could match anything with an = sign in it, that string would also have an '&' in it, so [^&=] is unnecessary.

like image 43
Steve P. Avatar answered Nov 02 '22 07:11

Steve P.