我有一个json

{
 "yes":
      {
       "en": "Yes",
       "de": "Ja"
      },
 "no":
      {
       "en": "No",
       "de": "Nein"
      }
}


我想要一个使用杰克逊的Java函数,它可以找到特定json值的最高密钥。

对于实例,如果我将值传递为Nein->,则应将位于顶层的no密钥作为输出。如何在Java中完成此操作?

最佳答案

好吧,您可以尝试执行以下操作:

   public static void getRootNodeOfJSONObject() throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonString = "{\"yes\":{\"en\": \"Yes\",\"de\": \"Ja\"},\"no\": {\"en\": \"No\",\"de\": \"Nein\"}}";
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        JsonNode jsonNodeRoot = objectMapper.readTree(jsonString);

        for (Iterator key = jsonNodeRoot.fields(); key.hasNext();) {
            String text = key.next().toString();
            if(text.contains("Nein"))
            {
                String rootElement = text.substring(0, text.indexOf("="));
                System.out.println("Root element: " + rootElement);
            }
        }
    }

    public static void main(String[] args) throws IOException {
        getRootNodeOfJSONObject();
    }

07-25 22:12
查看更多