61

Getting deprecated message for JsonParser for Spring Boot app,

JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();

What is the alternative?

Sazzad Hissain Khan
  • 37,929
  • 33
  • 189
  • 256
  • If the JsonPraser used is [this](https://javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/JsonParser.html#%3Cinit%3E()) , then the message says _No need to instantiate this class, use the static methods instead._ – R.G Mar 20 '20 at 09:26
  • Also you may use correct static method based on the `parse()` param – R.G Mar 20 '20 at 09:29
  • I am using `com.google.code.gson:gson:2.8.6` – Sazzad Hissain Khan Mar 20 '20 at 09:34
  • No `parse()` method available for JsonParser class – Sazzad Hissain Khan Mar 20 '20 at 09:35
  • The code shared shows `parse(result)` method used, there are alternative static methods for the `result` type. What is the type of the `result` parameter ? String , Reader or JsonReader ? – R.G Mar 20 '20 at 09:37

2 Answers2

106

Based on the javadoc for Gson 2.8.6

No need to instantiate this class, use the static methods instead.

and following are the alternatives to be used.

// jsonString is of type java.lang.String
JsonObject jsonObject = JsonParser.parseString​(jsonString).getAsJsonObject();

// reader is of type java.io.Reader
JsonObject jsonObject = JsonParser.parseReader​(reader).getAsJsonObject();

// jsonReader is of type com.google.gson.stream.JsonReader
JsonObject jsonObject = JsonParser.parseReader​(jsonReader).getAsJsonObject();

Example

import static org.junit.Assert.assertTrue;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class Test {

    public static void main(String[] args) {
        String jsonString = "{ \"name\":\"John\"}";

        JsonObject jsonObjectAlt = JsonParser.parseString(jsonString).getAsJsonObject();
        // Shows deprecated warning for new JsonParser() and parse(jsonString)
        JsonObject jsonObject = new JsonParser().parse(jsonString).getAsJsonObject();

        assertTrue(jsonObjectAlt.equals(jsonObject));

    }
}
double-beep
  • 5,031
  • 17
  • 33
  • 41
R.G
  • 6,436
  • 3
  • 19
  • 28
0

new GsonBuilder().setPrettyPrinting().create().toJson(new JSONParser(jsonString).parse());

vijay
  • 1
  • 2
  • 3
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – biasedbit Jan 30 '23 at 02:02