views:

94

answers:

1

Sure I do something wrong, but can't realize what :) I populate a key/value pair collection Map keyValuePairs with data, after I try to check collection for specific key existence in a common way keyValuePairs.containsKey("Name") and get back "false". But keyValuePairs.keySet() gives back set of keys where "Name" exists.

public static void parseBusinessObject(String input, Object output) {

Class parsingObject = output.getClass();
Field[] fields = parsingObject.getDeclaredFields();

Pattern pattern = Pattern.compile("([^{=;]*)=([^;}]*);");
Matcher matcher = pattern.matcher(/*input*/"anyType{Id=1; Name=Til afskrivning; LocationId=1; Editable=true; Default=true; Transcribed=false; }");
Map<String, String> keyValuePairs = new HashMap<String, String>();
while (matcher.find()) {
    if(!keyValuePairs.containsKey(matcher.group(1))){
    keyValuePairs.put(matcher.group(1).trim(), matcher.group(2).trim());
}
}

for (Field field : fields) {
    if(keyValuePairs.containsKey(field.getName())){
        //TODO: add values to fields    
    }
}
}

output result after matching:

 Id=1;
 Name=Til afskrivning;
 LocationId=1;
 Editable=true;
 Default=true;
 Transcribed=false;

"keyValuePairs"= HashMap (id=830062742672) { LocationId=1, Default=true, Editable=true, Name=Til afskrivning, Id=1, Transcribed=false}

"keyValuePairs.keySet()"= HashMap$1 (id=830062763448)
[ LocationId, Default, Editable, Name, Id, Transcribed]

"keyValuePairs.containsKey("Name")"= false

Could anybody please explain me what's wrong with it? Thank you.

+3  A: 

Quoting the information you gave in the question:

"keyValuePairs.keySet()"= HashMap$1  (id=830062763448)  
[ LocationId,  Default,  Editable,  Name, Id,  Transcribed]

The extra spaces in front of some of the key names suggest that the key inserted was " Name" (note the preceding space). If you give more information about the regex, we may be able to figure out why this happened.

You can also debug this yourself by logging/printing what group(1) and group(2) matches; I'm sure you'll find that it matches the extra whitespaces.

A quick fix is to put group(1).trim() and group(2).trim() into the map instead, but the better option is to fix the regex.

polygenelubricants
I'm going to guess the regex is something like `([^=]*)=(...)`. The solution may just be to add `\s*` in front of group 1.
polygenelubricants
U r absolutely correct, thank you!
Maxim
@Maxim: if you give enough information, I may be able to convince you to use `Scanner` instead. Or perhaps some other specialized libraries to handle key/value pairs, `java.util.Properties` et.al.
polygenelubricants
Question is edited, seems added everything, it's quite simple method to parse each property of soap response.
Maxim
@Maxim: I have no experience with SOAP, but check out http://stackoverflow.com/questions/1468428/how-to-extract-data-from-a-soap-response-in-java
polygenelubricants