Convert InputStream into JSON

前端 未结 3 1505
不知归路
不知归路 2020-12-16 11:31

I am using json-rpc-1.0.jar.Below is my code. I need to convert InputStream object into JSON since the response is in JSON.

I did verify the json response obtained f

3条回答
  •  醉梦人生
    2020-12-16 12:11

    Better to save memory by having output as Stream

    
        private fun InputStream.toJsonNodeStream(): Stream {
            return StreamSupport.stream(
                    Spliterators.spliteratorUnknownSize(this.toJsonNodeIterator(), Spliterator.ORDERED),
                    false
            )
        }
    
        private fun InputStream.toJsonNodeIterator(): Iterator {
            val jsonParser = objectMapper.factory.createParser(this)
    
            return object: Iterator {
    
                override fun hasNext(): Boolean {
                    var token = jsonParser.nextToken()
                    while (token != null) {
                        if (token == JsonToken.START_OBJECT) {
                            return true
                        }
                        token = jsonParser.nextToken()
                    }
                    return false
                }
    
                override fun next(): JsonNode {
                    return jsonParser.readValueAsTree()
                }
            }
        }
    
    

提交回复
热议问题