【问题标题】:JsonParser is deprecatedJsonParser 已弃用
【发布时间】:2020-07-01 10:14:36
【问题描述】:

获取 Spring Boot 应用程序的 JsonParser 已弃用消息,

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

有什么替代方案?

【问题讨论】:

  • 如果使用的 JsonPraser 是 this ,那么消息说不需要实例化这个类,而是使用静态方法。
  • 您也可以使用基于parse() 参数的正确静态方法
  • 我正在使用com.google.code.gson:gson:2.8.6
  • 没有可用于 JsonParser 类的 parse() 方法
  • 共享的代码显示使用了parse(result) 方法,result 类型还有其他静态方法。 result 参数的类型是什么? String , Reader 还是 JsonReader ?

标签: spring spring-boot parsing gson jsonparser


【解决方案1】:

基于 Gson 2.8.6 的 javadoc

不需要实例化这个类,使用静态方法代替。

以下是要使用的替代方法。

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

例子

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

    }
}

【讨论】:

  • 在我使用 JsonObject jsonObject = JsonParser.parseString​(result).getAsJsonObject(); 之后得到 java.lang.UnsupportedOperationException: JsonObject
  • result 类型是什么?它应该是一个字符串对象
  • 类型为JsonObject
  • JsonParser.parseString​(jsonString).getAsJsonObject(); 这里的参数应该是String 对象。对您来说,参数名称是 result ,将其转换为 String 并尝试。 (可能是.toString()
  • 检查。这是与问题共享的代码的记录替代方案
猜你喜欢
  • 2016-02-04
  • 2014-02-12
  • 1970-01-01
  • 2016-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-20
相关资源
最近更新 更多