Compare the key of a JSON Object to a String

1k Views Asked by At

I am trying to compare the key of a JSON Object to a String to assess whether or not my JSON Object contains the specified value at that key before continue processing. Here is a sample of the String .

{'type':'Layout','subType':'REPEATGRID','pgRef':'.pySections(1).pySectionBody(1).pyTable.pyRows(1).pyCells(3).pySections(1)'}

Here is the code I used to perform the evaluation. Let's assume the String above is store in a variable str

jsonString = str.replaceAll("\'", "\"");
JSONParser parser = new JSONParser();
JSONObject jsonObject = (JSONObject) parser.parse(jsonString);
System.out.println((String) jsonObject.get("subType") == "REPEATGRID");

The code above returns false while the statement System.out.println((String) jsonObject.get("subType")); returns REPEATGRID

Why is the evaluation returning false? How can I properly evaluate this situation?

PS: I am using org.json.simple library.

1

There are 1 best solutions below

1
On

try to use equals() instead of ==

   System.out.println((String) jsonObject.get("subType").equals("REPEATGRID"));

Further more,to aovid NullPointerException,you can improve as above:

   System.out.println("REPEATGRID".equals((String) jsonObject.get("subType")));