raj N ish Ku M ar raj N ish Ku M ar - 3 months ago 31
JSON Question

Not able to compare two json files with gson?

Hi i am trying to compare two JSON below is my code in Java

String json1 = "C:\\test1.json";
String json2 = "C:\\test2.json";

Gson g = new Gson();
Type mapType = new TypeToken<Map<String, Object>>(){}.getType();
Map<String, Object> firstMap = g.fromJson(json1, mapType);
Map<String, Object> secondMap = g.fromJson(json2, mapType);
System.out.println(Maps.difference(firstMap, secondMap));


and below is my JSON file format

My Json 1

{
"00601":{
"type":"zipcode",
"assignment":"South Monroe, MI"
},
"00602":{
"type":"zipcode",
"assignment":"South Monroe, MI"
},
"00603":{
"type":"zipcode",
"assignment":"South Monroe, MI"
}
}


My Json 2

{
"00601":{
"type":"zipcode",
"assignment":"South Monroe, MI"
},
"00602":{
"type":"zipcode",
"assignment":"South Monroe, MI"
},
"00603":{
"type":"zipcode",
"assignment":"South Monroe, MI"
}
}


i have gone through JSON Error "java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $"

but still facing the issue

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING


please help.

Answer

The value of json1, which is C:\test1.json internally, is not valid JSON, and similarly for json2. They looks like names of files which contain JSON. If so, you need to either:

  • read the contents of the (each) file into a String, possibly going through other types like a StringBuilder or CharBuffer on the way, and pass that String to .fromJson

  • create a Reader that reads the contents of the file, and pass that to the .fromJson(Reader,Type) method instead of the (String,Type) one; if the data in the file is in or compatible with your JVM's default encoding (and ASCII-only data such as your example is compatible with all encodings used as JVM defaults) then FileReader is suitable for this and can be constructed from a filename with new FileReader(String) as documented here

In a serious or larger program you should be careful to close a FileReader, or other method of reading the file like a FileInputStream, after using it to avoid tying up resources. Assuming Java8, try-with-resources is usually the most convenient way to do this.

Comments