如何在Java中比较yaml文件的键和内容?

huangapple go评论93阅读模式
英文:

How to compare the keys and the content of a yaml-file in Java?

问题

我想找一个能够比较两个YAML文件内容的框架。

我找到了一个链接,里面介绍了如何在Ruby中实现这个功能。
https://stackoverflow.com/questions/6274126/how-to-compare-keys-in-yaml-files

但我正在寻找一个Java框架来实现这个功能。

如果结果能够像“git diff”命令一样显示,那就太好了。

谢谢。

英文:

I want to find a framework,
which is able to compare the content of two yaml-files.

I found a link, how they describe it in ruby.
https://stackoverflow.com/questions/6274126/how-to-compare-keys-in-yaml-files

But I am searching for a Java-Framework for it.

It would be nice, if the result can be shown like a "git diff" command.

Thanks

答案1

得分: 3

你可以使用[zjsonpatch][1]和jackson-yaml进行比较...

添加以下依赖:

    implementation 'com.flipkart.zjsonpatch:zjsonpatch:0.4.10'
    implementation 'com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:2.9.8'

尝试以下代码:

    import com.fasterxml.jackson.databind.JsonNode;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
    import com.flipkart.zjsonpatch.JsonDiff;
    
    import java.io.File;
    
    public class Main {
    
        public static void main(String[] args) throws Exception{
            ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory());
            JsonNode file1 = objectMapper.readTree(new File("/your/file/path/file1.yml"));
            JsonNode file2 = objectMapper.readTree(new File("/your/file/path/file2.yml"));
            JsonNode patch = JsonDiff.asJson(file1, file2);
            String diffs = patch.toString();
            System.out.println(diffs);
        }
    }

  [1]: https://github.com/flipkart-incubator/zjsonpatch
英文:

You can compare by using zjsonpatch and jackson-yaml...

add below dependency:

implementation 'com.flipkart.zjsonpatch:zjsonpatch:0.4.10'
implementation 'com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:2.9.8'

Try with this:

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.flipkart.zjsonpatch.JsonDiff;

import java.io.File;

public class Main {

    public static void main(String[] args) throws Exception{
        ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory());
        JsonNode file1 = objectMapper.readTree(new File("/your/file/path/file1.yml"));
        JsonNode file2 = objectMapper.readTree(new File("/your/file/path/file2.yml"));
        JsonNode patch = JsonDiff.asJson(file1, file2);
        String diffs = patch.toString();
        System.out.println(diffs);
    }
}

huangapple
  • 本文由 发表于 2020年5月2日 15:36:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/61555920.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定