Java json String

java string转json怎么实现

小亿
130
2023-11-16 10:06:24
栏目: 编程语言

要将一个Java String对象转换为JSON格式,可以使用JSON库,如Jackson或Gson。以下是使用Jackson库的示例代码:

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.JsonProcessingException;

public class Main {
    public static void main(String[] args) {
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonString = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}";

        try {
            // 将String转换为JSON对象
            Object json = objectMapper.readValue(jsonString, Object.class);

            // 将JSON对象转换为格式化的字符串
            String formattedJson = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(json);
            System.out.println(formattedJson);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }
}

在上面的示例代码中,我们先创建了一个ObjectMapper对象。然后,使用readValue()方法将String对象转换为JSON对象。接下来,使用writerWithDefaultPrettyPrinter()方法将JSON对象转换为格式化的字符串,最后打印出来。

请注意,上述示例代码中的JSON字符串实际上是一个有效的JSON格式,如果你要将一个普通的字符串转换为JSON格式,你需要先构建一个JSON对象,然后将其转换为字符串。例如:

import com.fasterxml.jackson.databind.ObjectMapper;

public class Main {
    public static void main(String[] args) {
        ObjectMapper objectMapper = new ObjectMapper();
        String string = "Hello, world!";

        try {
            // 将普通字符串转换为JSON对象
            Object json = objectMapper.writeValueAsString(string);

            // 将JSON对象转换为格式化的字符串
            String formattedJson = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(json);
            System.out.println(formattedJson);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }
}

使用Gson库也可以实现相同的功能。以下是使用Gson库的示例代码:

import com.google.gson.Gson;

public class Main {
    public static void main(String[] args) {
        Gson gson = new Gson();
        String jsonString = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}";

        // 将String转换为JSON对象
        Object json = gson.fromJson(jsonString, Object.class);

        // 将JSON对象转换为格式化的字符串
        String formattedJson = gson.toJson(json);
        System.out.println(formattedJson);
    }
}

需要注意的是,以上示例代码中的JSON字符串必须是一个有效的JSON格式。如果你要将一个普通的字符串转换为JSON格式,你需要先构建一个JSON对象,然后将其转换为字符串。例如:

import com.google.gson.Gson;

public class Main {
    public static void main(String[] args) {
        Gson gson = new Gson();
        String string = "Hello, world!";

        // 将普通字符串转换为JSON对象
        Object json = gson.toJsonTree(string);

        // 将JSON对象转换为格式化的字符串
        String formattedJson = gson.toJson(json);
        System.out.println(formattedJson);
    }
}

无论是使用Jackson还是Gson,都需要将相应的库添加到项目的依赖中。你可以在官方网站上找到这些库的下载和使用说明。

0
看了该问题的人还看了