8

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
    ...
}
vivek
  • 4,599
  • 3
  • 25
  • 37

7 Answers7

6

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])
W A K A L E Y
  • 817
  • 1
  • 10
  • 14
  • Yes right . Just to make it more readable i took few minutes more than you. – W A K A L E Y Jul 09 '13 at 11:35
  • 1
    @JREN i think initializing the value in constructor makes more sense as Some can call get for values right after the creation of object. In that case as the values are not initiated it will throw error – W A K A L E Y Jul 09 '13 at 11:45
3
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.

Steve P.
  • 14,489
  • 8
  • 42
  • 72
  • If you're unfamiliar with regex, to get this to compile, `Pattern` and `Matcher` are from `java.util.regex`. – Steve P. Jul 09 '13 at 12:05
2

Split your string into pieces and then set them using your setters.

String str = "key1=value1&key2=value2&key3=value3";
String[] split = str.split("&");

MyClass obj = new MyClass();

obj.setKey1(split[0].split("=")[1]);
obj.setKey2(split[1].split("=")[1]);
obj.setKey3(split[2].split("=")[1]);

The first split, splits the string at the & symbol.

key1=value1 [0]

key2=value2 [1]

key3=value [2]

After that, you split each of those on the = symbol

key1 [0][0]

value1 [0][1]

key2 [1][0]

value2 [1][1]

key3 [2][0]

value3 [2][1]

So as in the first code block, you have split[0].split("=")[1] which is [0][1] in the explanation below. That's value1

It's quick & dirty but it works perfectly fine :)

Community
  • 1
  • 1
JREN
  • 3,572
  • 3
  • 27
  • 45
1

Try using beanutils and map

String[] keys = "key1=value1&key2=value2&key3=value3".split("&");
HashMap keyMap = new HashMap();
for(String key:keys){
String[] pair = key.split("=");
keyMap.put(pair[0],pair[1]);
}
MyClass  myCls=new MyClass();
BeanUtils.populate(myCls,keyMap);
vikrant singh
  • 2,091
  • 1
  • 12
  • 16
1

With Guava you can do this:

String str = "key1=value1&key2=value2&key3=value3";
Map<String, String> map = Splitter.on('&').withKeyValueSeparator("=").split(str);

and than you can do with the keys and values whatever you want. E.g.

mc.setKey1(map.get("key1")); // will set key1 to value1
jlordo
  • 37,490
  • 6
  • 58
  • 83
0

This can be done by using the split element in java Store your string in variable and call the split methord in java.

string = "key1=value1&key2=value2&key3=value3";
String[] keys = string.split("&");

IN the next step you can perform a split on each of the elements of the the array keys using the '=' character.

Ref : How to split a string in Java

Community
  • 1
  • 1
user2120239
  • 135
  • 2
  • 10
0
You can use java reflection :

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class MyClass {

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

  public void setKey1(String key1) {
    this.key1 = key1;
  }

  public void setKey2(String key2) {
    this.key2 = key2;
  }

  public void setKey3(String key3) {
    this.key3 = key3;
  }

  public void setKey(String input) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
    String[] strings = input.split("&");
    String methodName = null;
    Method setter = null;
    for(String keyValue : strings) {
      String[] keyValuePair = keyValue.split("=");
      methodName = toSetterMethod(keyValuePair[0]);
      setter = getMethod(methodName);
      if (setter != null) {
        setter.setAccessible(true);
        setter.invoke(this, keyValuePair[1]);
      }
    }
  }

  private Method getMethod(String methodName) {
    try {
      Method[] methods = MyClass.class.getMethods();
      for (Method method : methods) {
        if (method.getName().equals(methodName)) {
          return method;
        }
      }
    } catch (SecurityException e) {
    }
    return null;

  }

  private String toSetterMethod(String property) {
    String setter = "set";
    setter += property.substring(0, 1).toUpperCase() + property.substring(1);
    return setter;
  }
  public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
    String input = "key1=value1&key2=value2&key3=value3";
    MyClass myClass = new MyClass();
    myClass.setKey(input);

    System.out.println(myClass.key1);
    System.out.println(myClass.key2);
    System.out.println(myClass.key3);


  }

}
Nguyen
  • 1
  • 3