Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

144
Views
ObjectMapper readValue

I load a ressource file json with the text format

{
    "sources": [{
            "prop1": "1",
            "prop2": "2"

        },
        {
            "prop1": "1",
            "prop2": "2"

        },
    ],
    "redirection": [{
            "prop1": "1",
            "prop2": "2"

        }
    ]
}

I have a class with this properties prop1 and prop2

I want to recover with ObjectMapper a list class. What the method ?

This code doesn't work ....

 Map<String, Object> mp =  mapper.readValue(jsonResource.getInputStream(),new TypeReference<Map<String, Object>>() {});
String sourceText= new ObjectMapper().readTree(jsonResource.getInputStream()).get("sources").asText();

 mapper.readValue(sourceText, new TypeReference<List<MyClass>>(){});

Thanks for your help

about 4 years ago · Santiago Trujillo
3 answers
Answer question

0

In your case, I would write a custom JsonDeserializer. Haven't really tested the code, but I think the idea is clear:

    final MyClassDeserializer myClassDeserializer = new MyClassDeserializer();
    final SimpleModule deserializerModule = new SimpleModule();
    deserializerModule.addDeserializer(MyClass.class, myClassDeserializer);

    final ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(deserializerModule);

And the code for JsonDeserializer:

    public class MyClassDeserializer extends JsonDeserializer<MyClass> {

    @Override
    public MyClass deserialize(final JsonParser jsonParser, final DeserializationContext context)
            throws IOException {
        final JsonNode node = jsonParser.getCodec().readTree(jsonParser);
        final JsonNode sourcesNode = node.get("sources");
        if(node.isArray()) {
            final ArrayNode arrayNode = (ArrayNode) node;
            final Iterable<JsonNode> nodes = arrayNode::elements;
            final Set<Source> set = StreamSupport.stream(nodes.spliterator(), false)
                    .map(mapper)
                    .collect(Collectors.toSet());
            ...
        }

        ...
    }
about 4 years ago · Santiago Trujillo Report

0

First thing: Your JSON is invalid. There is a comma after the second object in the sources array. This has to be deleted.

Second: I think you didn't choose the right type for your result. What your JSON represents is a map which maps from string to an array of objects. So the type should be something like Map<String, Props[]> (Since you didn't provide the name of your class, I called it Props.

With these considerations you can construct a MapType by using ObjectMappers getTypeFactory() method and deserialize the value using the constructed type like shown below.

ObjectMapper mapper = new ObjectMapper();
TypeFactory typeFactory = mapper.getTypeFactory();
MapType mapType = typeFactory.constructMapType(HashMap.class, String.class, Props[].class);
Map<String, Props[]> map = mapper.readValue(s, mapType);
about 4 years ago · Santiago Trujillo Report

0

I actually voted for the other answer, but this is my idea, to create the classes and let jackson do the work :

public class ResourceTest {

    @Test
    public void test1() throws IOException {
        assertTrue(true);

        Resource resource = new Resource();

        resource.getRedirectrions().add(makeRedirectrion("rprop11", "rprop12"));
        resource.getRedirectrions().add(makeRedirectrion("rprop21", "rprop22"));

        resource.getSources().add(makeSource("sprop11","sprop12"));
        resource.getSources().add(makeSource("sprop21","sprop22"));

        String json = new ObjectMapper().writeValueAsString(resource);
        System.out.println(json);

        Resource resource1 = new ObjectMapper().readValue(json, Resource.class);
        System.out.println(resource1);
    }

    private Source makeSource(String prop1, String prop2) {
        Source source = new Source();
        source.setProp1(prop1);
        source.setProp2(prop2);
        return source;
    }

    private Redirectrion makeRedirectrion(String prop1, String prop2) {
        Redirectrion redirectrion = new Redirectrion();
        redirectrion.setProp1(prop1);
        redirectrion.setProp2(prop2);
        return redirectrion;
    }

}

Output is:

{"sources":[{"prop1":"sprop11","prop2":"sprop12"},{"prop1":"sprop21","prop2":"sprop22"}],"redirectrions":[{"prop1":"rprop11","prop2":"rprop12"},{"prop1":"rprop21","prop2":"rprop22"}]}
Resource{sources=[Source{prop1='sprop11', prop2='sprop12'}, Source{prop1='sprop21', prop2='sprop22'}], redirectrions=[Source{prop1='rprop11', prop2='rprop12'}, Source{prop1='rprop21', prop2='rprop22'}]}
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!