Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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
    ...
}
share|improve this question
Does your class need to store keys or values for keys? – Pshemo Jul 9 at 11:27
@vivek, if you don't want to use split, check out my answer (using regex). – Steve P. Jul 9 at 11:47
2  
Just wondering what can be the reason for not using split? Is it a assignment? – user1614217 Jul 9 at 12:05
@user1614217 Perhaps, but perhaps he assumed that there way a way to do it without splitting and wanted to know how it could be done. – Steve P. Jul 9 at 12:24
@SteveP. ya right i just wanted to check only thats why my comment. – user1614217 Jul 9 at 12:54

7 Answers

up vote 3 down vote accepted
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.

share|improve this answer
If you're unfamiliar with regex, to get this to compile, Pattern and Matcher are from java.util.regex. – Steve P. Jul 9 at 12:05

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])
share|improve this answer
This is basically what I said, only harder to read. – JREN Jul 9 at 11:34
Yes right . Just to make it more readable i took few minutes more than you. – user1614217 Jul 9 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 – user1614217 Jul 9 at 11:45

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 :)

share|improve this answer
Isn't there some other way without using split method – vivek Jul 9 at 11:30
@vivek you can use a StringTokenizer if you really want to avoid the split method. mkyong.com/java/java-stringtokenizer-example – JREN Jul 9 at 11:41
1  
@vivek, yes, there is. See my answer. – Steve P. Jul 9 at 11:52
+1 for Steve P. nice answer – JREN Jul 9 at 11:53
@JREN Thanks! You got one, too. – Steve P. Jul 9 at 11:55

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);
share|improve this answer
+1 for proposing a standard Apache library – parasietje Jul 9 at 14:40

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 : string split in java

share|improve this answer

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
share|improve this answer
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);


  }

}
share|improve this answer
without using split method? was part of the question – Manuel Jul 9 at 12:21
sorry, but I think "split" method is not a big problem. You can do it by yourself. – Nguyen Jul 9 at 12:44

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.