Search code examples
javajsonjacksonjackson-databind

JsonString value to extract specific key


Spec : JARS used Jackson for Json parsing /extraction in Java (JDK-15)

Statement : String val1 = "[ {"UnitId":"106","CategoryId":"403","ProductId":"103 ","ProductName":"California Apples","ProductWeight":"250"} ]";

Question : I need to extract values of "ProductName" from the Json Verified String.

Problem : I need to use Jakson jar libraries Only to parse & extract. I have tried sample code using jackson libraries on stackoverflow...did not work.

If some body has sample code to try, please share.

with regard Karthik


Solution

  • As an option, if you don't want create object for that. You can do like this:

        private static JsonMapper JSON_MAPPER = new JsonMapper();
    
        public static String parseProductId(String rawJson) {
        try {
            JsonNode root = JSON_MAPPER.readTree(rawJson);
            return root.get(0).get("ProductId").asText();
        } catch (JsonProcessingException e) {
            throw new IllegalArgumentException("Some information");
        }
    }
    

    In my opinion, this method gives flexibility if we need 1-2 fields.