#Repository: javaReflectionJson
##Problem definition and solution
This implementation deals with the problem that data from a JSON file are correctly converted into a generic object tree during the process of deserialization by the GSON library. To determine this, GSON also creates a concrete Java object model with a root element. This is traversed level by level and using the Reflection API, the fields of the current object are determined and their values compared with those of the generic object tree. If something is different in the comparison, the return value is set to false, otherwise the java object model and the generic object tree are the same and the return value is set to true.
##How to use the implementation
####Adding the methods The JSON file is parsed and either a generic object tree or a tree of concrete object types (like the given "company" or "position" class) is created. You can also use your own classes and JSON files to compare their contents with this implementation.
- store the JSON file you want to deserialize in the inputs directory
- add the Java Object model corresponding to the JSON file in the "src/main/java/model" directory
- open the class GsonParser in the "src/main/java/features" directory
- copy one of the methods - either parseToCompany or parseToPosition
- change the return value to your root class type and the method body as in the following snippet
public static YourClassType parseToYourClassType(String file) throws IOException
{
Gson gson = new Gson();
JsonReader reader;
YourClassType yourObject = new YourClassType();
reader = new JsonReader(new FileReader(file));
yourObject = gson.fromJson(reader, yourObject.getClass());
reader.close();
return yourObject;
}
####Testing the methods The generic tree created when applying the "parseToTree" method on a JSON file is compared to the "concrete" tree when deserialize the file to a specific object (e.g. "parseToCompany" or "parseToYourClass"). It is checked whether these two trees contain the same data.
- open the test class CompareTreesTest in the "src/test/java" directory
- create a new constant with your path to the JSON file
- initialize a root object of your Java object model as in the following snippet
private YourClassType yourObject;
@Before
public void setUp() throws Exception
{
yourObject = GsonParser.parseToYourClassType(YOUR_FILEPATH);
}
- create a new test method with the code line like below
assertTrue(ObjTreeComparator.validate(yourObject, YOUR_FILEPATH));
- run this method to test it on your file