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.

Bharath M
  • 128
  • 1
  • 3
  • 14
  • 1
    Possible duplicate of [Convert InputStream into JSON](https://stackoverflow.com/questions/18794427/convert-inputstream-into-json) – Butiri Dan Jul 24 '19 at 11:11
  • 1
    Possible duplicate of [How do I read / convert an InputStream into a String in Java?](https://stackoverflow.com/questions/309424/how-do-i-read-convert-an-inputstream-into-a-string-in-java) – Vitalii Vitrenko Jul 24 '19 at 11:12
  • Isn't JSON way more suited to write to a log file than a Map.toString()? – cfrick Jul 24 '19 at 14:45

2 Answers2

0

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

objectMapper.readValue(is, Map.class);
MD Ruhul Amin
  • 4,386
  • 1
  • 22
  • 37
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")
daggett
  • 26,404
  • 3
  • 40
  • 56
  • 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. – Sneftel Jul 24 '19 at 14:01