1

I want to compare whether the keys of two Gson converted objects are the same.

Example: I have one JSON object in a file customer.json which is stored locally:

{
  name:"John",
  age:25
}

There is an API which gives the same JSON data from a custom volley request which I am converting to a Customer POJO.

Now I want to determine whether the JSON data stored locally and the JSON data received from the API are the same.

I am reading the JSON file and converting it to a Customer as follows:

InputStream is = getContext().getResources().openRawResource(
    R.raw.customerjson);
Gson gson = new Gson();
Reader reader = null;
reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
Customer customerLocal = gson.fromJson(reader, Customer.class);

Now I have both of the converted Customer objects (customerLocal and customerServer).

Everything is working fine; the problem is that I don't know how to compare the two Gson converted objects. Note that I want to compare only the keys (i.e. the variable name in the POJO, not the value).

Any help is greatly appreciated.

Eric Galluzzo
  • 3,191
  • 1
  • 20
  • 20
John
  • 8,846
  • 8
  • 50
  • 85
  • why don't you compare in string form?? – Vivek Mishra Jan 06 '16 at 12:26
  • I thought this.But volley response will give me the converted pojo not string. And more over we are using custom volley request which is all over the project so cannot change the custom request and response – John Jan 06 '16 at 12:28
  • By pojo do you mean to say bean object?? – Vivek Mishra Jan 06 '16 at 12:30
  • Plain Old Java Object - POJO – Reaz Murshed Jan 06 '16 at 12:30
  • Simply Iterate over the JSON object and compare the keys. http://stackoverflow.com/questions/9151619/java-iterate-over-jsonobject – Adam Jenkins Jan 06 '16 at 12:30
  • Anyway, I think you missed the conversion to a json string after you read the response data from InputStream. `BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line); }` Then `sb.toString();` to find the string. – Reaz Murshed Jan 06 '16 at 12:32
  • gson.fromJson(reader, Customer.class); will convert from reader to string and then Customer class – John Jan 06 '16 at 13:07
  • Shouldn't it just be a java object comparison once you have both Customer objects (customerLocal and customerServer)? Something similar to http://stackoverflow.com/questions/16069106/how-to-compare-two-java-objects by provideing your own implementation of equals() – random Jan 12 '16 at 09:49

1 Answers1

1

I have solved it. By converting the gson converted object back to json like below

JSONObject serverJsonObject = new JSONObject(gson.toJson(customerResponse));

Then compared serverJsonObect with locally stored json object with assertJsonEquals method from JsonUnit Library

My test cases are working fine now.

John
  • 8,846
  • 8
  • 50
  • 85