2014-10-07 54 views
3

我正在處理配置文件,所以我需要將JSON轉換爲YAML。 比如我有YAML文件:將JSON轉換爲YAML。解析JSON到YAML

{ 
    "foo": "bar", 
    "baz": [ "qux","quxx"], 
    "corge": null, 
    "grault": 1, 
    "garply": true, 
    "waldo": "false", 
    "fred": "undefined", 
    "emptyArray": [], 
    "emptyObject": {}, 
    "emptyString": "" 
} 

結果應該是YAML:

foo: "bar" 
baz: 
    - "qux" 
    - "quxx" 
corge: null 
grault: 1 
garply: true 
waldo: "false" 
fred: "undefined" 
emptyArray: [] 
emptyObject: {} 
emptyString: "" 

你能幫助我嗎?

回答

1

如果你需要轉換的JSONObject到YAML(串)。你需要。首先得到json字符串,然後映射,然後你可以轉換爲yaml。 下面的代碼:

// this is your json object 
    JSONObject jsonobject = new JSONObject(map); 
    // get json string 
    String prettyJSONString = jsonobject.toString(4); 
    // mapping 
    Map<String,Object> map = (Map<String, Object>) yaml.load(prettyJSONString); 
    // convert to yaml string (yaml formatted string) 
    String output = yaml.dump(map2); 
+2

你能簡單解釋一下你的答案嗎?你在哪裏聲明「jsonPrettyPrintString」 – 2015-06-06 07:14:55

+0

我很抱歉遲到的迴應,我編輯了答案。 @MurugesanEra – eabyshev 2016-03-15 13:49:27

+1

這段代碼片段使用了什麼框架/庫? – 2016-12-09 20:24:48

-1

http://jsontoyaml.com/

本網站可能會幫助你。它可以在 猛砸, JavaScript的使用, JavaScript的(唯一的瀏覽器), 紅寶石, Python和Perl的 , 的Java ..

+0

是的,我看到這個網站,但我需要在java代碼... – eabyshev 2014-10-07 12:37:08

+0

我反對這個投票。沒有提到提供「程序化方式」的問題,所以這個答案也是有效的。 – 2018-01-15 11:49:10

8

可以轉換JSON與兩行代碼YAML它Jackson

import java.io.IOException; 

import com.fasterxml.jackson.core.JsonProcessingException; 
import com.fasterxml.jackson.databind.JsonNode; 
import com.fasterxml.jackson.databind.ObjectMapper; 
import com.fasterxml.jackson.dataformat.yaml.YAMLMapper; 

public class Library { 

    public String asYaml(String jsonString) throws JsonProcessingException, IOException { 
     // parse JSON 
     JsonNode jsonNodeTree = new ObjectMapper().readTree(jsonString); 
     // save it as YAML 
     String jsonAsYaml = new YAMLMapper().writeValueAsString(jsonNodeTree); 
     return jsonAsYaml; 
    } 

} 

您將需要依賴添加到傑克遜的核心,而DataBind已DATAFORMAT YAML。下面是Gradle的一個片段:

compile 'com.fasterxml.jackson.core:jackson-core:2.8.6' 
compile 'com.fasterxml.jackson.core:jackson-databind:2.8.6' 
compile 'com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:2.8.6'