Getting deprecated message for JsonParser
for Spring Boot app,
JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
What is the alternative?
Deprecated. No need to instantiate this class, use the static methods instead.
Interface JsonParser. Provides forward, read-only access to JSON data in a streaming way. This is the most efficient way for reading JSON data. The class Json contains methods to create parsers from input sources ( InputStream and Reader ).
The JSON Parser reads and writes entries using the JavaScript Object Notation (JSON) format. JSON is a lightweight data-interchange format and a subset of JavaScript programming language. JSON is built using the following two structures: An ordered list of values (array) A collection of name/value pairs (object)
According to the documentation of JSONParser, the class is not thread safe. So you either need proper locking or create one parser per thread.
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)); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With