【问题标题】:Extracting JSON Keys from Two Dimensional Matrix从二维矩阵中提取 JSON 键
【发布时间】:2020-01-21 19:04:52
【问题描述】:

在处理表示二维矩阵的有效 JSON 时:

[ { "a":1, "b":2 }, { "b":3, "c":4 }, { "c":6, "a":5 } ]

使用 Java 1.8 和 json-simple 库:

<dependency>
  <groupId>com.googlecode.json-simple</groupId>
  <artifactId>json-simple</artifactId>
  <version>1.1.1</version>
</dependency>

是否能够使用以下方法获得单独的行?:

JSONParser parser = new JSONParser();
Object obj = parser.parse(args[0]);
JSONArray array = (JSONArray) obj;
System.out.println(array.get(0));

这个输出:

{"a":1,"b":2}

我的问题是如何从这个二维矩阵中提取键值来输出:

'{ "a": [1,null,5], "b": [2,3,null], "c": [null,4,6] }'

请注意,行中缺少的任何变量都应插入 null...

【问题讨论】:

    标签: java json json-simple


    【解决方案1】:

    一般解决方案如下所示:

    1. JSON 有效负载读取为ARRAY
    2. ARRAY 中的所有 JSON Object 中查找所有可能的键,并将它们存储在 KEYS 集中。
    3. 遍历 ARRAY 中的所有 JSON Object
      1. 遍历所有 KEYS 并从给定的JSON Object 中获取值或null

    使用Java 8 功能我们可以实现如下:

    import org.json.simple.JSONArray;
    import org.json.simple.JSONObject;
    import org.json.simple.parser.JSONParser;
    import org.json.simple.parser.ParseException;
    
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    import java.util.Set;
    import java.util.stream.Collectors;
    
    public class JsonSimpleApp {
        public static void main(String[] args) throws ParseException {
            // input
            String json = "[ { \"a\":1, \"b\":2 }, { \"b\":3, \"c\":4 }, { \"c\":6, \"a\":5 } ]";
    
            // read as JSONArray
            JSONParser parser = new JSONParser();
            JSONArray array = (JSONArray) parser.parse(json);
    
            // Find all possible keys
            Set<String> keys = (Set<String>) array.stream().flatMap(i -> ((JSONObject) i).keySet().stream()).collect(Collectors.toSet());
    
            // create result Map with KEY - LIST pair
            Map<String, List<Object>> result = new HashMap<>();
            keys.forEach(key -> result.put(key, new ArrayList<>()));
    
            // Iterate over all JSONObject's
            array.forEach(item -> {
                JSONObject object = (JSONObject) item;
                // For each possible key add a value or NULL to each list
                keys.forEach(key -> result.get(key).add(object.remove(key)));
            });
    
            result.entrySet().forEach(System.out::println);
        }
    }
    

    上面的代码打印:

    a=[1, null, 5]
    b=[2, 3, null]
    c=[null, 4, 6]
    

    【讨论】:

      【解决方案2】:

      你可以通过key访问json。例如:

      obj["key"][0]
      

      那么就可以取值了

      【讨论】:

      • 你能告诉我如何通过 Java 代码做到这一点吗?
      • 能否请您删除这个答案,因为它没有回答这个问题?
      【解决方案3】:

      已编辑

      您只需使用 JOLT 即可。

      JSONJSON 转换库,用 Java 编写,其中 转换的“规范”本身就是一个 JSON 文档。

      根据你的场景,你必须:

      1- 创建规则

      2- 通过此规则过滤您的输入。


      • JSON 输入如下
      [
        {
          "a": 1,
          "b": 2
        },
        {
          "b": 3,
          "c": 4
        },
        {
          "c": 6,
          "a": 5
        }
      ]
      
      • 过滤器规则(JOLT规范)可以如下
      [
         {
           "operation": "shift",
           "spec": {
      
             "*": {
               "a": "a",
               "b": "b",
               "c": "c"
             }
      
           }
         }
      ]
      
      • 结果
      {
        "a" : [ 1, 5 ],
        "b" : [ 2, 3 ],
        "c" : [ 4, 6 ]
      }
      

      您可以在here中测试上述解决方案


      • 在 java 中应用上述项目的 Java 代码
      public class CustomJsonTransformer {
      
          public static void main(String[] args) throws Exception {
      
              //Get filter (JOLT SPEC)
              List<Object> specs = JsonUtils.classpathToList("/filter.json");
              Chainr chainr = Chainr.fromSpec(specs);
      
              //Get input JSON
              Object inputJSON = JsonUtils.classpathToObject("/input.json");
      
              //Do filter
              Object transformedOutput = chainr.transform(inputJSON);
      
              //Result
              System.out.println(JsonUtils.toPrettyJsonString(transformedOutput));
          }
      }
      

      1- This guide 展示了一个非常好的 java JOLT 示例

      2- JOLT 的完整文档是here

      请注意,在 JOLT 文档的帮助下,您可以使规则更复杂或更简单(我的规则只是一个简单的规则)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-05-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-04
        相关资源
        最近更新 更多