Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JsonParser is deprecated

Getting deprecated message for JsonParser for Spring Boot app,

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

What is the alternative?

like image 494
Sazzad Hissain Khan Avatar asked Mar 20 '20 09:03

Sazzad Hissain Khan


People also ask

Is JSONParser deprecated?

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

What is the use of JSONParser in Java?

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 ).

What is a JSONParser?

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)

Is org JSON simple parser JSONParser thread safe?

According to the documentation of JSONParser, the class is not thread safe. So you either need proper locking or create one parser per thread.


1 Answers

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));      } } 
like image 108
R.G Avatar answered Sep 20 '22 14:09

R.G