PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, May 19, 2022

[FIXED] how to convert LinkedHashMap to Custom java object?

 May 19, 2022     java, json, web-services     No comments   

Issue

I'm trying to get the data from one app to another via RESTful WS and it works, but I cannot use this data since I cannot cast it... WS returns a List of objects like this:

{id=1, forename=John, surname=Bloggs, username=jbloggs, role=Graduate Developer, office=London, skills=[{technology=Java, experience=2.5}, {technology=Web, experience=2.0}, {technology=iOS, experience=0.0}, {technology=.NET, experience=0.0}]}

to get I it use Jackson's ObjectMapper:

ObjectMapper mapper = new ObjectMapper();

    List<ConsultantDto> list = new ArrayList<ConsultantDto>();


    try {

        list = mapper.readValue(con.getInputStream(), ArrayList.class);

    } catch (JsonGenerationException e) {

        e.printStackTrace();

    } catch (JsonMappingException e) {

        e.printStackTrace();

    } catch (IOException e) {

        e.printStackTrace();

    }

after that I have 3 lines of code:

System.out.println(list.get(0));
System.out.println(list.get(0).getForename());
return list;

return because this method's return value is passed to other webservice which displays correct data in a browser. Interesting thing happens with two printing lines, one prints the data from the top of this post ({id:1 ... }) but the other one throws exception:

java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.xxx.xxx.web.dto.rp.ConsultantDto

ConsultantDto and SkillDto are two legit classes which have all properties set to match the data from WS, all getters/setters are in place. As far as I'm concerned LinkedHashMap stores stuff as key:value pairs, so I just don't see where is this exception coming from. How can I fix it and why doesn't ObjectMapper just parse the value correctly (which it does when I get a single ConsultantDto rather than a List)?


Solution

You need to do this:

List<ConsultantDto> myObjects =
    mapper.readValue(jsonInput, new TypeReference<List<ConsultantDto>>(){});

(From this SO answer)

The reason you have to use TypeReference is because of an unfortunate quirk of Java. If Java had a proper generics, I bet your syntax would have worked.



Answered By - Enno Shioji
Answer Checked By - Willingham (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing