可以使用com.alibaba.fastjson.JSON类的parseObject方法将YAML格式的字符串转换为com.alibaba.fastjson.JSONObject对象。

示例代码如下:

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.yaml.snakeyaml.Yaml;

public class YamlToJsonConverter {
    public static JSONObject convert(String yamlString) {
        Yaml yaml = new Yaml();
        Object yamlObject = yaml.load(yamlString);
        String jsonString = JSON.toJSONString(yamlObject);
        return JSON.parseObject(jsonString);
    }

    public static void main(String[] args) {
        String yamlString = 'name: John
age: 25
';
        JSONObject jsonObject = convert(yamlString);
        System.out.println(jsonObject);
    }
}

运行以上代码,输出结果为:

{"age":25,"name":"John"}

可以看到,YAML格式的字符串已成功转换为com.alibaba.fastjson.JSONObject对象。

将YAML字符串转换为JSON对象 - 使用 Fastjson 和 SnakeYAML

原文地址: https://www.cveoy.top/t/topic/p19J 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录