java yaml 解析,如何在Java中将YAML转换为JSON?

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

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

in a String called yamlDoc:

String yamlDoc = "---\npaper:\n uuid: 8a... etc...";

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

String yamlDoc = "---\npaper:\n uuid: 8a... etc...";

String json = convertToJson(yamlDoc); // I want this method

System.out.println(json);

should print:

{

"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"

}

}

]

}

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

I tried to achieve this using SnakeYAML, so this code

Yaml yaml = new Yaml();

Map map = (Map) yaml.load(yamlDoc);

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.

Any response will be greatly appreciated.

解决方案

Thanks to HotLicks tip (in the question comments) I finally achieve the conversion using the libraries org.json and SnakeYAML in this way:

private static String convertToJson(String yamlString) {

Yaml yaml= new Yaml();

Map map= (Map) yaml.load(yamlString);

JSONObject jsonObject=new JSONObject(map);

return jsonObject.toString();

}

I don't know if it's the best way to do it, but it works for me.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值