Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Query on Java Jackson Implementation

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

`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);
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading