0

I am trying to compare two JSON strings. 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
halfer
  • 19,824
  • 17
  • 99
  • 186
Rajnish Kumar
  • 2,828
  • 5
  • 25
  • 39
  • So the issue is `Gson#fromJson` throwing some exception? Maybe you could rephrase the question and post the full stacktrace.. –  Aug 10 '16 at 10:35

1 Answers1

1

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.

dave_thompson_085
  • 34,712
  • 6
  • 50
  • 70