Ali
Ali

Reputation: 267077

How to get a String value from a Map <String, String[] > in Java?

Basically, I have a Map<String, String[] > which contains a bunch of strings with a key. If I do String value = myMap.get("keyName");, this returns an Object rather than a string, and echoing it produces something like this: Ljava.lang.String;@1dfa166. Doing toString() doesn't help either.

What do I need to do to get the value as string:

My code looks like this:

String value ="" + request().body().asFormUrlEncoded().get("keyName");

Here the asFormUrlEncoded() method is what returns the Map

Upvotes: 0

Views: 20296

Answers (1)

Shawn D.
Shawn D.

Reputation: 8125

You're getting back an array of strings (second parameter to the generic Map as declared).

Change it to

String [] values = myMap.get( "keyName" );

and check values.length to see how many strings are in the array. If it's just one, you can just access it as values[0].

The reason it allows for a string array is because each key in the form could have multiple values, so it can't return a single string.

Upvotes: 6

Related Questions