Convert a Map value to String

Deadly 提交于 2020-06-29 03:51:16

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!