问题
I am trying to convert a map value to String
.
I tried toString()
method but it still returns an Object
instead of String
response = WS.sendRequest(findTestObject('api/test/TD-4_01_01-Valid'))
Map parsed = response.getHeaderFields()
String messageId = parsed.get('x-message-id').toString();
println messageId
Actual Output:
[C5yZC5hcy5sb2NhbC0xMjgyNi05MzE1LTE=]
Expected Output:
C5yZC5hcy5sb2NhbC0xMjgyNi05MzE1LTE=
回答1:
ResponseObject#getHeaderFields returns a Map
of String
keys to a List
of String
objects as vales. You simply need to get the List
of String
objects for the key x-message-id
and since you expect it to return a single result, find any.
ResponseObject response = WS.sendRequest(findTestObject('api/test/TD-4_01_01-Valid'));
Map<String, List<String>> parsed = response.getHeaderFields();
List<String> messageIdList = parsed.get("x-message-id");
String messageId = messageIdList.stream().findAny().orElseThrow(IllegalStateException::new);
回答2:
According to the API, the Map
is a Map<String, List<String>>
mapping. This is why you get the wrapping with brackets []
.
If you want to access the first element in this list, you should call parsed.get('x-message-id').get(0)
to access the element with index 0.
Here is the full solution:
response = WS.sendRequest(findTestObject('api/test/TD-4_01_01-Valid'))
Map parsed = response.getHeaderFields()
String messageId = parsed.get('x-message-id').get(0);
println messageId
来源:https://stackoverflow.com/questions/62407710/convert-a-map-value-to-string