Java Generic Map not converted to proper type in runtime for Json converstion












4















I have one method which works fine when i use actual class, but don't give expected output when using generics.



Below is the method which works fine when using ABC class



public static List<ABC> getMemberViewRepresentation(Response response) throws JSONException, IOException {
JSONObject jsonObj = new JSONObject(response.readEntity(String.class));
ObjectMapper mapper = new ObjectMapper();
JSONObject memberViewObj = (JSONObject)jsonObj.get("members");
TypeReference<HashMap<String, ABC>> typeRef = new TypeReference<HashMap<String, ABC>>() {};
Map<String, ABC> map = mapper.readValue(memberViewObj.toString(), typeRef);
return new ArrayList<>(map.values());
}


This methods gives proper output which has list of type ABC.



But i want to write code such that i pass class dynamically so that this method can be used by anyone. So i have written below code, also i tried other way but none of them seems to work.



public static<T> List<T> getMemberViewRepresentation(Response response) throws JSONException, IOException {
JSONObject jsonObj = new JSONObject(response.readEntity(String.class));
ObjectMapper mapper = new ObjectMapper();
JSONObject memberViewObj = (JSONObject)jsonObj.get("members");
TypeReference<HashMap<String, T>> typeRef = new TypeReference<HashMap<String, T>>() {};
Map<String, T> map = mapper.readValue(memberViewObj.toString(), typeRef);
return new ArrayList<>(map.values());
}
I am calling in this way
List<ABC> nodes = ResponseUtil.getMemberViewRepresentation(response);


But the output of above method is not same. List is not of type ABC



@JsonIgnoreProperties(ignoreUnknown = true)
public class ABC {
@JsonProperty("id")
private int id;
@JsonProperty("uid")
private String uid;

public int getId() {
return id;
}

public String getUid() {
return uid;
}
}


Any idea how to keep the method dynamic such that i can pass Class details separately










share|improve this question



























    4















    I have one method which works fine when i use actual class, but don't give expected output when using generics.



    Below is the method which works fine when using ABC class



    public static List<ABC> getMemberViewRepresentation(Response response) throws JSONException, IOException {
    JSONObject jsonObj = new JSONObject(response.readEntity(String.class));
    ObjectMapper mapper = new ObjectMapper();
    JSONObject memberViewObj = (JSONObject)jsonObj.get("members");
    TypeReference<HashMap<String, ABC>> typeRef = new TypeReference<HashMap<String, ABC>>() {};
    Map<String, ABC> map = mapper.readValue(memberViewObj.toString(), typeRef);
    return new ArrayList<>(map.values());
    }


    This methods gives proper output which has list of type ABC.



    But i want to write code such that i pass class dynamically so that this method can be used by anyone. So i have written below code, also i tried other way but none of them seems to work.



    public static<T> List<T> getMemberViewRepresentation(Response response) throws JSONException, IOException {
    JSONObject jsonObj = new JSONObject(response.readEntity(String.class));
    ObjectMapper mapper = new ObjectMapper();
    JSONObject memberViewObj = (JSONObject)jsonObj.get("members");
    TypeReference<HashMap<String, T>> typeRef = new TypeReference<HashMap<String, T>>() {};
    Map<String, T> map = mapper.readValue(memberViewObj.toString(), typeRef);
    return new ArrayList<>(map.values());
    }
    I am calling in this way
    List<ABC> nodes = ResponseUtil.getMemberViewRepresentation(response);


    But the output of above method is not same. List is not of type ABC



    @JsonIgnoreProperties(ignoreUnknown = true)
    public class ABC {
    @JsonProperty("id")
    private int id;
    @JsonProperty("uid")
    private String uid;

    public int getId() {
    return id;
    }

    public String getUid() {
    return uid;
    }
    }


    Any idea how to keep the method dynamic such that i can pass Class details separately










    share|improve this question

























      4












      4








      4








      I have one method which works fine when i use actual class, but don't give expected output when using generics.



      Below is the method which works fine when using ABC class



      public static List<ABC> getMemberViewRepresentation(Response response) throws JSONException, IOException {
      JSONObject jsonObj = new JSONObject(response.readEntity(String.class));
      ObjectMapper mapper = new ObjectMapper();
      JSONObject memberViewObj = (JSONObject)jsonObj.get("members");
      TypeReference<HashMap<String, ABC>> typeRef = new TypeReference<HashMap<String, ABC>>() {};
      Map<String, ABC> map = mapper.readValue(memberViewObj.toString(), typeRef);
      return new ArrayList<>(map.values());
      }


      This methods gives proper output which has list of type ABC.



      But i want to write code such that i pass class dynamically so that this method can be used by anyone. So i have written below code, also i tried other way but none of them seems to work.



      public static<T> List<T> getMemberViewRepresentation(Response response) throws JSONException, IOException {
      JSONObject jsonObj = new JSONObject(response.readEntity(String.class));
      ObjectMapper mapper = new ObjectMapper();
      JSONObject memberViewObj = (JSONObject)jsonObj.get("members");
      TypeReference<HashMap<String, T>> typeRef = new TypeReference<HashMap<String, T>>() {};
      Map<String, T> map = mapper.readValue(memberViewObj.toString(), typeRef);
      return new ArrayList<>(map.values());
      }
      I am calling in this way
      List<ABC> nodes = ResponseUtil.getMemberViewRepresentation(response);


      But the output of above method is not same. List is not of type ABC



      @JsonIgnoreProperties(ignoreUnknown = true)
      public class ABC {
      @JsonProperty("id")
      private int id;
      @JsonProperty("uid")
      private String uid;

      public int getId() {
      return id;
      }

      public String getUid() {
      return uid;
      }
      }


      Any idea how to keep the method dynamic such that i can pass Class details separately










      share|improve this question














      I have one method which works fine when i use actual class, but don't give expected output when using generics.



      Below is the method which works fine when using ABC class



      public static List<ABC> getMemberViewRepresentation(Response response) throws JSONException, IOException {
      JSONObject jsonObj = new JSONObject(response.readEntity(String.class));
      ObjectMapper mapper = new ObjectMapper();
      JSONObject memberViewObj = (JSONObject)jsonObj.get("members");
      TypeReference<HashMap<String, ABC>> typeRef = new TypeReference<HashMap<String, ABC>>() {};
      Map<String, ABC> map = mapper.readValue(memberViewObj.toString(), typeRef);
      return new ArrayList<>(map.values());
      }


      This methods gives proper output which has list of type ABC.



      But i want to write code such that i pass class dynamically so that this method can be used by anyone. So i have written below code, also i tried other way but none of them seems to work.



      public static<T> List<T> getMemberViewRepresentation(Response response) throws JSONException, IOException {
      JSONObject jsonObj = new JSONObject(response.readEntity(String.class));
      ObjectMapper mapper = new ObjectMapper();
      JSONObject memberViewObj = (JSONObject)jsonObj.get("members");
      TypeReference<HashMap<String, T>> typeRef = new TypeReference<HashMap<String, T>>() {};
      Map<String, T> map = mapper.readValue(memberViewObj.toString(), typeRef);
      return new ArrayList<>(map.values());
      }
      I am calling in this way
      List<ABC> nodes = ResponseUtil.getMemberViewRepresentation(response);


      But the output of above method is not same. List is not of type ABC



      @JsonIgnoreProperties(ignoreUnknown = true)
      public class ABC {
      @JsonProperty("id")
      private int id;
      @JsonProperty("uid")
      private String uid;

      public int getId() {
      return id;
      }

      public String getUid() {
      return uid;
      }
      }


      Any idea how to keep the method dynamic such that i can pass Class details separately







      java






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Oct 19 '18 at 8:07









      abhishek chaubalabhishek chaubal

      211




      211
























          1 Answer
          1






          active

          oldest

          votes


















          1














          I think, what you need is:



          List<ABC> nodes = ResponseUtil.<ABC>getMemberViewRepresentation(response);


          ...to infer the generic parameter(s) into a static method (WITHOUT typed parameter(s)).



          Note the extra <ABC> before method invocation!
          Normally you don't need it, because a regular generic method goes like:
          public static<T> void foo(T someInput) {...} ...and providing someInput, T is known/easy to infer at runtime. In your case Response has nothing to do with ABC...so can't be inferred (with anything else than ?).



          The first method works as expected, because there is no "generic method", while the "class generic type" seems to be inferred correctly (somewhere else in your code/configuration).



          The second doesn't, because the "generic method type" is missing (and i assume inferred as <?> respectively <java.lang.Object> ...so you get a List<Object> returned and assigned to your List<ABC>, which is not as expected, but at least "fail free").



          You can argument, that we can "infer" ABC from the return type (you expect a List<ABC>, where a List<T> is delivered), but unfortunately this is not how it works/this information is not available at that point/needs deeper study.






          share|improve this answer

























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f52888228%2fjava-generic-map-not-converted-to-proper-type-in-runtime-for-json-converstion%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            1














            I think, what you need is:



            List<ABC> nodes = ResponseUtil.<ABC>getMemberViewRepresentation(response);


            ...to infer the generic parameter(s) into a static method (WITHOUT typed parameter(s)).



            Note the extra <ABC> before method invocation!
            Normally you don't need it, because a regular generic method goes like:
            public static<T> void foo(T someInput) {...} ...and providing someInput, T is known/easy to infer at runtime. In your case Response has nothing to do with ABC...so can't be inferred (with anything else than ?).



            The first method works as expected, because there is no "generic method", while the "class generic type" seems to be inferred correctly (somewhere else in your code/configuration).



            The second doesn't, because the "generic method type" is missing (and i assume inferred as <?> respectively <java.lang.Object> ...so you get a List<Object> returned and assigned to your List<ABC>, which is not as expected, but at least "fail free").



            You can argument, that we can "infer" ABC from the return type (you expect a List<ABC>, where a List<T> is delivered), but unfortunately this is not how it works/this information is not available at that point/needs deeper study.






            share|improve this answer






























              1














              I think, what you need is:



              List<ABC> nodes = ResponseUtil.<ABC>getMemberViewRepresentation(response);


              ...to infer the generic parameter(s) into a static method (WITHOUT typed parameter(s)).



              Note the extra <ABC> before method invocation!
              Normally you don't need it, because a regular generic method goes like:
              public static<T> void foo(T someInput) {...} ...and providing someInput, T is known/easy to infer at runtime. In your case Response has nothing to do with ABC...so can't be inferred (with anything else than ?).



              The first method works as expected, because there is no "generic method", while the "class generic type" seems to be inferred correctly (somewhere else in your code/configuration).



              The second doesn't, because the "generic method type" is missing (and i assume inferred as <?> respectively <java.lang.Object> ...so you get a List<Object> returned and assigned to your List<ABC>, which is not as expected, but at least "fail free").



              You can argument, that we can "infer" ABC from the return type (you expect a List<ABC>, where a List<T> is delivered), but unfortunately this is not how it works/this information is not available at that point/needs deeper study.






              share|improve this answer




























                1












                1








                1







                I think, what you need is:



                List<ABC> nodes = ResponseUtil.<ABC>getMemberViewRepresentation(response);


                ...to infer the generic parameter(s) into a static method (WITHOUT typed parameter(s)).



                Note the extra <ABC> before method invocation!
                Normally you don't need it, because a regular generic method goes like:
                public static<T> void foo(T someInput) {...} ...and providing someInput, T is known/easy to infer at runtime. In your case Response has nothing to do with ABC...so can't be inferred (with anything else than ?).



                The first method works as expected, because there is no "generic method", while the "class generic type" seems to be inferred correctly (somewhere else in your code/configuration).



                The second doesn't, because the "generic method type" is missing (and i assume inferred as <?> respectively <java.lang.Object> ...so you get a List<Object> returned and assigned to your List<ABC>, which is not as expected, but at least "fail free").



                You can argument, that we can "infer" ABC from the return type (you expect a List<ABC>, where a List<T> is delivered), but unfortunately this is not how it works/this information is not available at that point/needs deeper study.






                share|improve this answer















                I think, what you need is:



                List<ABC> nodes = ResponseUtil.<ABC>getMemberViewRepresentation(response);


                ...to infer the generic parameter(s) into a static method (WITHOUT typed parameter(s)).



                Note the extra <ABC> before method invocation!
                Normally you don't need it, because a regular generic method goes like:
                public static<T> void foo(T someInput) {...} ...and providing someInput, T is known/easy to infer at runtime. In your case Response has nothing to do with ABC...so can't be inferred (with anything else than ?).



                The first method works as expected, because there is no "generic method", while the "class generic type" seems to be inferred correctly (somewhere else in your code/configuration).



                The second doesn't, because the "generic method type" is missing (and i assume inferred as <?> respectively <java.lang.Object> ...so you get a List<Object> returned and assigned to your List<ABC>, which is not as expected, but at least "fail free").



                You can argument, that we can "infer" ABC from the return type (you expect a List<ABC>, where a List<T> is delivered), but unfortunately this is not how it works/this information is not available at that point/needs deeper study.







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Nov 20 '18 at 11:47

























                answered Nov 20 '18 at 11:32









                xerx593xerx593

                2,4791429




                2,4791429






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f52888228%2fjava-generic-map-not-converted-to-proper-type-in-runtime-for-json-converstion%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Can a sorcerer learn a 5th-level spell early by creating spell slots using the Font of Magic feature?

                    Does disintegrating a polymorphed enemy still kill it after the 2018 errata?

                    A Topological Invariant for $pi_3(U(n))$