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

后端 未结 5 2364
囚心锁ツ
囚心锁ツ 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 16:02

    5 year late, but this was my solution:

    I converted the jsonParser to string

    String requestString = jsonParser.readValueAsTree().toString();
    

    Then I converted that string into a JsonParser

    JsonFactory factory = new JsonFactory();
    JsonParser parser  = factory.createParser(requestString);
    

    Then I iterated through my parser

    ObjectMapper objectMapper = new ObjectMapper();
    while(!parser.isClosed()){
        JsonToken jsonToken = parser.nextToken();
        if(JsonToken.FIELD_NAME.equals(jsonToken)){
            String currentName = parser.getCurrentName();
            parser.nextToken();
            switch (currentName) {
                case "someObject":
                    Object someObject = objectMapper.readValue(parser, Object.class)
                    //validate someObject
                    break;
            }
     }
    

    I needed to save the original json string for logging purposes, which is why I did this in the first place. Was a headache to find out, but finally did it and I hope i'm helping someone out :)

提交回复
热议问题