0

Suppose I have an InputStream that contains JSON data, and I want to convert it to a Map(Key Value Pairs), so for example I can write that to a log file.

What is the easiest way to take the InputStream and convert it to a Map?

public String convertInputStreamToMap(InputStream isobj) { // ??? } 

I've tried converting to String which works as expected but when the data is really long the data will be incomplete. So I want some easiest way to directly convert this to Map.

3

2 Answers 2

0

Use ObjectMapper from com.fasterxml.jackson.databind to directly convert inputstream to Map: for example:

objectMapper.readValue(is, Map.class); 
Sign up to request clarification or add additional context in comments.

Comments

0

there is a built-in class in groovy to parse json: groovy.json.JsonSlurper

it has parse method that accepts almost any source including InputStream

def url = 'https://httpbin.org/get'.toURL() def json = url.withInputStream{inputStream-> new groovy.json.JsonSlurper().parse(inputStream) } println json.headers 

and if you want to convert InputStream to String, groovy provides additional methods to work with InputStream class: https://docs.groovy-lang.org/latest/html/groovy-jdk/java/io/InputStream.html

the following code reads the content of this InputStream using specified charset and returns it as a String.

String s = inputStream.getText("UTF-8") 

1 Comment

While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.