Montaser
Montaser

Reputation: 69

Parsing Json response to a different Java object each time

I am using Jersey as a client to parse JSON into Java objects, The problem is that I am using a service that returns different types of responses that should be mapped to a different Java object each time, so I need a way to step into the parsing process and make an arbitrary decision to tell Jersey what is the exact type of object to parse each time.

EDIT:

For example if I have Java Classes A, B, and C and the Json Response as follows:

Data{ 
   -list {
      -0 :{Result should be mapped to A}
      -1 :{Result should be mapped to B}
      -2 :{Result should be mapped to C}
    }
}

and the list is ArrayList (or can be ArrayList of a super class for the three classes). Now when I ask Jersey to parse this JSON response, It will find an ArrayList when handling list and dosen't know what's the exact type of the object to parse into, so it convert the data inside -0, -1, -2 to a linkedHashMap as a key/value pairs.

Upvotes: 0

Views: 1366

Answers (1)

mgraff
mgraff

Reputation: 11

I use jackson in a jersey client to map json to a hashMap but the mapper will work for pojo's as well. Hope the following helps.

Get the list elements into an array/list. Loop through and determine the correct class for each element.
Pass each list element and its respective class name to a method that handles the mapping and returns an object.

    import ...
    import com.fasterxml.jackson.databind.ObjectMapper;

    public class RequestProcessor {
        void jerseyClient(){

            //rest request
            WebResource resource = ...
            ClientResponse responseContent =   resource.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); 

            List list = parseJSonResponse(responseContent);
            for (String jsonListElement : list){
                //determine correct class for jsonListElement

                //Pass jsonListElement and class name to mapper method
                Object obj = mapElementToObject(jsonListElement , className);

                //do something with obj
            }

        }

        private Object mapElementToObject(String jsonString, String className){
            ObjectMapper mapper = new ObjectMapper();
            Object obj = mapper.readValue(jsonString, Class.forName(className);
            return obj;
        }

        private List parseJsonResponse(responseContent){
            //use regexp to replace unnecessary content in response so you have a string
            //that looks like -0:{element values}-1:{element values}-2:{element values}

            //then split the string on "-.*\\:" into a array/list

            //return the list
        }

    }

Upvotes: 1

Related Questions