用Java解析Yaml

Dam*_*men 6 java yaml jackson jackson-databind

我有以下YAML我想Jackson在Java中使用解析器进行解析.

android:
    "7.0":
        - nexus
        - S8
    "6.0":
        - s7
        - g5
ios:
    "10.0":
        - iphone 7
        - iphone 8
Run Code Online (Sandbox Code Playgroud)

我创建了一个创建class具有gettersetter作为Java Objectandroid.它工作正常.但我怎么做同样6.07.0? I'm usingJackson`分析器

fly*_*lyx 5

不知道杰克逊是否支持;这是使用普通SnakeYaml的解决方案(我永远不会理解为什么人们使用Jackson解析YAML时,它所做的只是基本上消除了用作后端的SnakeYaml的详细配置):

class AndroidValues {
     // showing what needs to be done for "7.0". "8.0" works similarly.
     private List<String> v7_0;

     public List<String> getValuesFor7_0() {
         return v7_0;
     }

     public void setValuesFor7_0(List<String> value) {
         v7_0 = value;
     }
}

// ... in your loading code:

Constructor constructor = new Constructor(YourRoot.class);
TypeDescription androidDesc = new TypeDescription(AndroidValues.class);
androidDesc.substituteProperty("7.0", List.class, "getValuesFor7_0", "setValuesFor7_0");
androidDesc.putListPropertyType("7.0", String.class);
constructor.addTypeDescription(androidDesc);
Yaml yaml = new Yaml(constructor);

// and then load the root type with it
Run Code Online (Sandbox Code Playgroud)

注意:代码尚未经过测试。

  • 我对YAML领域还很陌生,并且一直在评估各种产品,而Jackson似乎确实在幕后使用SnakeYaml-所以我在问同样的问题,您是...为什么直接使用Jackson YAML而不直接使用SnakeYaml? (2认同)