Converting Using Generics | Core Java Forum
R
Ramya Seshan Posted on 02/12/2020

Hi  [Sir / Yogesh ],

  Below is snippet of code which i use to convert a JSON to class object of required class

Since i have 100 + API's , i end up repeating same set of code multiple times 

@Step ("Convert Strict Customer Match JSON file to Object")
public StrictCustomerMatch getStrictMatch() {
String Match = schemaDir+ "/Request/strictCustomerMatch.json";
StrictCustomerMatch StrictMatch= genson.fromJson(SchemaJsonReader.getReader(Match), StrictCustomerMatch.class);
return StrictMatch;
}

 

Issue: Since i have 100 + API's , i end up repeating same set of code multiple times .

When i tried making this function a generic one , it returns null pointer exception, Please help to resolve this

 @Step ("Convert Strict Customer Match JSON file to Object")
public <E> E getStrictMatch(E Data, String JSONName ) {
String Match = schemaDir+ "/Request/"+JSONName+".json";
E ValueReceived= genson.fromJson(SchemaJsonReader.getReader(Match), (Type) Object.class);
return ValueReceived;
}

 

Calling Statement:

Class<StrictCustomerMatch> StrictMatch= BASS.getStrictMatch(StrictCustomerMatch.class ,"strictCustomerMatch" );

 

 

 

 

 

  


Y
Yogesh Chawla Replied on 03/12/2020

Hi Ramya,

You can try something like this. I don't think there is any need to pass 'E Data' as method parameter because you are not using it anywhere.

And we can create one method convertInstanceOfObject to convert the instance to particular type which in this particular case is 'StrictCustomerMatch'. I can't test this entire peace because I don't have the complete code with me but you try to test the same and tell me if there is any exception coming in your code.

 

Class<StrictCustomerMatch> StrictMatch= BASS.getStrictMatch("strictCustomerMatch" );

	 @Step ("Convert Strict Customer Match JSON file to Object")
	 public <E> E getStrictMatch(String JSONName) {
	 //String Match = schemaDir+ "/Request/strictCustomerMatch.json";
	 String Match = schemaDir+ "/Request/"+JSONName+".json";
	 
	 E StrictMatch= genson.fromJson(SchemaJsonReader.getReader(Match), convertInstanceOfObject(Object.class));
	 return StrictMatch;
	 }
	 
	public static <T> T convertInstanceOfObject(Object o) {
		    try {
		       return (T) o;
		    } catch (ClassCastException e) {
		        return null;
		    }
		}