如何在 Java 中将 YAML 转换为 JSON?

How do I convert from YAML to JSON in Java?(如何在 Java 中将 YAML 转换为 JSON?)

本文介绍了如何在 Java 中将 YAML 转换为 JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想将一个包含 yaml 的字符串转换为另一个包含使用 Java 转换的对应 json 的字符串.

I just want to convert a string that contains a yaml into another string that contains the corrseponding converted json using Java.

例如假设我有这个 yaml 的内容

For example supose that I have the content of this yaml

---
paper:
   uuid: 8a8cbf60-e067-11e3-8b68-0800200c9a66
   name: On formally undecidable propositions of Principia Mathematica and related systems I.
   author: Kurt Gödel.
tags:
   - tag:
       uuid: 98fb0d90-e067-11e3-8b68-0800200c9a66
       name: Mathematics
   - tag:
       uuid: 3f25f680-e068-11e3-8b68-0800200c9a66
       name: Logic

在名为 yamlDoc 的字符串中:

in a String called yamlDoc:

String yamlDoc = "---
paper:
   uuid: 8a... etc...";

我想要一些可以将yaml字符串转换为另一个带有相应json的字符串的方法,即以下代码

I want some method that can convert the yaml String into another String with the corresponding json, i.e. the following code

String yamlDoc = "---
paper:
   uuid: 8a... etc...";
String json = convertToJson(yamlDoc); // I want this method
System.out.println(json);

应该打印:

{
    "paper": {
        "uuid": "8a8cbf60-e067-11e3-8b68-0800200c9a66",
        "name": "On formally undecidable propositions of Principia Mathematica and related systems I.",
        "author": "Kurt Gödel."
    },
    "tags": [
        {
            "tag": {
                "uuid": "98fb0d90-e067-11e3-8b68-0800200c9a66",
                "name": "Mathematics"
            }
        },
        {
            "tag": {
                "uuid": "3f25f680-e068-11e3-8b68-0800200c9a66",
                "name": "Logic"
            }
        }
    ]
}

我想知道在这个例子中是否存在类似于 convertToJson() 方法的东西.

I want to know if exists something similar to the convertToJson() method in this example.

我尝试使用 SnakeYAML 来实现这一点,所以这段代码

I tried to achieve this using SnakeYAML, so this code

 Yaml yaml = new Yaml();
 Map<String,Object> map = (Map<String, Object>) yaml.load(yamlDoc);

构造一个包含已解析 YAML 结构的映射(使用嵌套映射).然后,如果有一个解析器可以将地图转换为 json 字符串,它将解决我的问题,但我也没有找到类似的东西.

constructs a map that contain the parsed YAML structure (using nested Maps). Then if there is a parser that can convert a map into a json String it will solve my problem, but I didn't find something like that neither.

我们将不胜感激.

推荐答案

这是一个使用 Jackson 的实现:

Here is an implementation that uses Jackson:

String convertYamlToJson(String yaml) {
    ObjectMapper yamlReader = new ObjectMapper(new YAMLFactory());
    Object obj = yamlReader.readValue(yaml, Object.class);

    ObjectMapper jsonWriter = new ObjectMapper();
    return jsonWriter.writeValueAsString(obj);
}

要求:

compile('com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:2.7.4')

这篇关于如何在 Java 中将 YAML 转换为 JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何在 Java 中将 YAML 转换为 JSON?

基础教程推荐