java - 我应该如何声明 GSON 来反序列化 JSON 字符串?

标签 java gson

我在代码中使用 Java Callable Future。下面是我的主要代码,它使用了 future 和 callables -

下面是我的主要代码,它使用了 future 和 callables -

public class TimeoutThread {

    public static void main(String[] args) throws Exception {

        ExecutorService executor = Executors.newFixedThreadPool(5);
        Future<String> future = executor.submit(new Task());

        try {
            System.out.println(future.get(3, TimeUnit.SECONDS));
        } catch (TimeoutException e) {

        }

        executor.shutdownNow();
    }
}

下面是我的 Task 类,它实现了 Callable 接口(interface),在该接口(interface)中我使用 RestTemplate 对我的服务器进行 REST URL 调用。然后使用 GSON 反序列化 JSON 字符串。

class Task implements Callable<String> {
    private static RestTemplate restTemplate = new RestTemplate();

    @Override
    public String call() throws Exception {

    String url = "some_url";            
    String response = restTemplate.getForObject(url, String.class);

    TestResponse jsonResponse = new Gson().fromJson(response, TestResponse.class);
    }
}

所以我的问题是我应该如何在这里声明GSON?是否应该在 Task 类中将其声明为静态全局变量? Bcoz 目前我正在使用 gson 解析 JSON,并且每次调用 new Gson() 这会很昂贵吗?

最佳答案

Gson类的源代码在这里:https://code.google.com/p/google-gson/source/browse/trunk/gson/src/main/java/com/google/gson/Gson.java

它只有 final 字段,因此它的内部状态是不可变的。所有引用的集合都包装为 synchronizedMapunmodifiableListtoJsonfromJson 方法主要依赖于局部变量。因此共享同一个实例是安全的。

关于java - 我应该如何声明 GSON 来反序列化 JSON 字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21324764/

相关文章:

android - GSON getAsString() 方法不会从 JSON 元素中去除双引号?

java - 如何使用 jama 声明矩阵

java - 使用 webdriver 找不到元素

java - 在Java中,相同类型但不同类型参数的空集合总是相等吗?

android - 如何使用 GSON 解析 JSON,以获取 JSONObject 未按需要解析的错误 JSON?

java - 如何使用变量中提供的类型使用 GSON.fromJson ?

java - 反序列化多维数组GSON

java - 如何通过 SSL 实现 Web 服务到 Web 服务的通信?

Java - Spring 的 ReactorNettyWebSocketClient 线程安全吗?

Java - 使用 Gson 序列化 Iterable<Map.Entry<>>