【问题标题】:Fetch Highest Parent Key for a JSON value using jackson使用jackson获取JSON值的最高父键
【发布时间】:2019-03-29 06:16:41
【问题描述】:

我有一个json

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

我想要一个使用 jackson 的 java 函数,它可以为特定的 json 值找到可能的最高键。

例如,如果我将值传递为Nein -> 那么位于顶层的no 键应该是输出。我怎样才能在java中完成这个??

【问题讨论】:

  • 你能详细说明你想要什么吗?
  • @MS90 我已经完成了可能的更改!!

标签: java json jackson key fetch


【解决方案1】:

好吧,您可以尝试以下方法:

   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();
    }

【讨论】:

    【解决方案2】:

    你可以试试 JsonPath (https://github.com/json-path/JsonPath)。

    关注“谓词”部分。

    如果您需要任何帮助,请告诉我。

    【讨论】:

      猜你喜欢
      • 2022-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-29
      • 1970-01-01
      相关资源
      最近更新 更多