Есть ли способ сравнить ключи двух файлов свойств с различной структурой? - PullRequest
1 голос
/ 02 ноября 2019

У меня есть два файла свойств +10.000 строк с различной структурой, и мне нужно знать, какие ключи есть в обоих файлах.

Я попытался использовать такие инструменты, как WinMerge и FileMerge, без какой-либо удачи.

File1:

.
.
.
  "CardShipmentScale.shipmentScaleRegional": "SomeText1",
  "CardShipmentScale.shipmentScaleRegionalExplanation": "SomeText2",
  "CheckboxCard.DAY": "SomeText3",
  "CheckboxCard.MONTH": "SomeText4",
  "SomeOtherKey.SomeOtherSubKey": "SomeOtherText5"
.
.
.

File2:

{ "global" : {
.
.
.
      CardShipmentScale : {
          shipmentScaleRegional : "SomeText1",
          shipmentScaleRegionalExplanation : "SomeText2"
                          },
      SomeOtherKey : {
          SomeOtherSubKey : "SomeOtherText5"
                     },

.
.
.

}

В этом примере я хотел бы получить отчет о программе, который указывает, что CardShipmentScale был найден в файлах file1 и file2, ноCheckboxCard только в файле1.

Есть идеи?

1 Ответ

1 голос
/ 02 ноября 2019

Вы можете начать с этого ответа Уплощение 3-уровневой вложенной строки JSON в java . Я создал там JsonFlattener, который преобразует JSON файл в Map, где ключом является JSON Path.

Теперь должно быть легко проверить каждый ключ из первого файла во втором файле:

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.introspect.Annotated;
import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;

public class JsonPathApp {

    public static void main(String[] args) throws Exception {
        File jsonFile0 = new File("./resource/test.json").getAbsoluteFile();
        File jsonFile1 = new File("./resource/test1.json").getAbsoluteFile();

        ObjectMapper mapper = new ObjectMapper();
        Map<String, JsonNode> map0 = new JsonFlattener(mapper.readTree(jsonFile0)).flatten();
        Map<String, JsonNode> map1 = new JsonFlattener(mapper.readTree(jsonFile1)).flatten();

        for (Map.Entry<String, JsonNode> node : map0.entrySet()) {
            String keyToCheck = "/global" + node.getKey().replace('.', '/');
            if (map1.containsKey(keyToCheck)) {
                System.out.println(node.getKey() + " exists in both files.");
            } else {
                System.out.println(node.getKey() + " exists only in 1 file.");
            }
        }
    }
}

test.json содержит:

{
  "CardShipmentScale.shipmentScaleRegional": "SomeText1",
  "CardShipmentScale.shipmentScaleRegionalExplanation": "SomeText2",
  "CheckboxCard.DAY": "SomeText3",
  "CheckboxCard.MONTH": "SomeText4",
  "SomeOtherKey.SomeOtherSubKey": "SomeOtherText5"
}

test1.json содержит:

{
  "global": {
    "CardShipmentScale": {
      "shipmentScaleRegional": "SomeText1",
      "shipmentScaleRegionalExplanation": "SomeText2"
    },
    "SomeOtherKey": {
      "SomeOtherSubKey": "SomeOtherText5"
    }
  }
}

Для вышеуказанных файлов приложение печатает:

/CardShipmentScale.shipmentScaleRegional exists in both files.
/CardShipmentScale.shipmentScaleRegionalExplanation exists in both files.
/CheckboxCard.DAY exists only in 1 file.
/CheckboxCard.MONTH exists only in 1 file.
/SomeOtherKey.SomeOtherSubKey exists in both files.
...