JsonParser is deprecated

怎甘沉沦 提交于 2020-08-24 06:37:12

问题


Getting deprecated message for JsonParser for Spring Boot app,

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

What is the alternative?


回答1:


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

    }


来源:https://stackoverflow.com/questions/60771386/jsonparser-is-deprecated

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!