How to get the underlying String from a JsonParser (Jackson Json)

后端 未结 5 2161
囚心锁ツ
囚心锁ツ 2021-02-18 15:23

Looking through the documentation and source code I don\'t see a clear way to do this. Curious if I\'m missing something.

Say I receive an InputStream from a server resp

5条回答
  •  礼貌的吻别
    2021-02-18 15:53

    What you are trying to do is outside the scope of Jackson (and most, if not all other Java JSON libraries out there). What you want to do is fully consume the input stream into a string, then attempt to convert that string to a JSON object using Jackson. If the conversion fails then do something with the intermediate string, else proceed normally. Here's an example, which utilizes the excellent Apache Commons IO library, for convenience:

    final InputStream stream ; // Your stream here
    
    final String json = IOUtils.toString(stream);
    try {
        final JsonNode node = new ObjectMapper().readTree(json);
        // Do something with JSON object here
    } catch(final JsonProcessingException jpe) {
        // Do something with intermediate string here
    }
    

提交回复
热议问题