Query on Java Jackson Implementation

Advertisements

I have a json file in below format:

{   
   "resources" : {     
        "foo" : {       
          "value" : "test"      
         },     
        "bar" : {       
          "value" : "test"     
         }    
   } 
}

And, I have created it’s JAVA Class as below:

package org.example.model;

import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.HashMap;
import java.util.List;

public class JsonTwoJavaFileModel {
   @JsonProperty("resources")
   private HashMap<String, HashMap<String, List<String>>>  stringListHashMap;
}

However, getting below error while reading it:

`Exception in thread "main" com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `java.util.ArrayList` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('test')  at [Source: (File); line: 4, column: 17] (through reference chain: org.example.model.JsonTwoJavaFileModel["resources"]->java.util.HashMap["offer1"]->java.util.HashMap["value"])`

Not sure, how to create Java class for such type of nested JSONs. Any pointer to solve it?

Also tried creating Java Class like below:

`package org.example.model;

import com.fasterxml.jackson.annotation.JsonProperty;    
import java.util.HashMap;
import java.util.List;

public class JsonTwoJavaFileModel {
   @JsonProperty("resources")
   private HashMap<List<String>, HashMap<String, List<String>>> stringListHashMap;
}`

But no luck with both approach.

>Solution :

try this something like this:

  @Test
  public void testJackson() throws JsonProcessingException {
    ObjectMapper objectMapper = new ObjectMapper();

    String json = "{\"resources\":{\"foo\":{\"value\":\"test\"},\"bar\":{\"value\":\"test\"}}}";
    HashMap<String, HashMap<String, HashMap<String, String>>> mapped = objectMapper.readValue(
            json,
            new TypeReference<>() {
              @Override
              public Type getType() {
                return super.getType();
              }
            });
    assertNotNull(mapped);
  }
}

Leave a ReplyCancel reply