从LinkedHashMap中检索值 [英] Retrieve value from a LinkedHashMap

查看:107
本文介绍了从LinkedHashMap中检索值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的对象:

I have an Object that looks like this:

{
/test1: {
  get: {
   tags: [
     "restcalls"
   ]
 }
},
/test2: {
  put: {
   tags: [
     "restcalls"
   ]
 }
}
}

我正在检索上面这样的对象:

I am retrieving above object like this:

HashMap<?, ?> json = new ObjectMapper().readValue(str, HashMap.class);

但是检索标签的最佳方法是什么并用其他关键字替换它们,让我们说我的休息电话。请注意,get,put也可以是任何其他变量名,所以它的动态但标签总是在get,put。

But what would be the best way to retrieve tags and replace them with some other keyword lets say "my rest calls". Please note, get, put can be any other variable names too so its dynamic but tags will be always under get, put.

推荐答案

您已经选择 Jackson 作为您的Java-JSON库(我可以说是好的选择)所以你手上的问题是如何使用Jackson以最佳方式遍历和更新JSON,但是那些甚至决定使用哪个Java-JSON库的人可以读取这里比较下面提到的7个Java-JSON库。以下是链接的结论摘录:

You have already chosen Jackson as your Java-JSON library (which I could say is a good choice) so problem at your hand is how to use Jackson to traverse and update the JSON in best way, but those who are even deciding on which Java-JSON library to use can read here which compares below mentioned 7 Java-JSON libraries. Below is conclusion excerpt from link:


作为结论,如果您知道您将仅使用小$ b您的应用程序中的$ b数据量,并且您希望将其存储或读取为
,并且从JSON格式,您应该考虑使用Flexjson或Gson 。如果
你打算使用大量数据并希望以jSON格式存储或读取
,你应该考虑使用Jackson或
JSON-lib

As a conclusion, if you know that you are going to use only a small amount of data in your application and you wish to store or read it to and from JSON format, you should consider using Flexjson or Gson. If you are going to use large amounts of data and wish to store or read it to and from JSON format, you should consider using Jackson or JSON-lib.




  • Jackson

  • Google-GSON

  • JSON-lib

  • Flexjson

  • json-io

  • genson

  • JSONiJ

    • Jackson
    • Google-GSON
    • JSON-lib
    • Flexjson
    • json-io
    • genson
    • JSONiJ

    • 最重要的是要了解Jackson提供了三种处理JSON的替代方法(阅读更多这里),因此应根据具体要求明智地选择合适的方法。

      Most important thing to understand is that Jackson offers three alternative methods for processing JSON (read more here), so appropriate approach should be chosen wisely considering the specific requirements.


      1. Streaming API 又名增量解析/生成):它读取和写入JSON内容为离散事件。 最佳案例使用:迭代事件(或令牌)流。 类似于: SAX和Stax

      1. Streaming API (aka "Incremental parsing/generation"): It reads and writes JSON content as discrete events. Best case use: Iterating over Event (or, token) stream. Analogous to: SAX and Stax

      树模型: 它提供JSON文档的可变内存树表示。树模型类似于XML DOM。 最佳用例:将Json数据绑定到Java对象中。 类似于: JAXB

      Tree Model: It provides a mutable in-memory tree representation of a JSON document. The tree model is similar to the XML DOM. Best case use: Binding Json data into Java Objects. Analogous to: JAXB

      数据绑定: 它将JSON转换为以及基于属性访问器约定或注释的POJO。有两种变体:简单和完整数据绑定。 最佳案例使用:构建树结构(来自Json)并使用合适的方法遍历它。 类似于: DOM

      Data Binding: It converts JSON to and from POJOs based either on property accessor conventions or annotations. There are two variants: simple and full data binding. Best case use: Building a tree structure (from Json) and traversing it using suitable methods. Analogous to: DOM


      • 简单数据绑定意味着与Java地图进行转换,列表,字符串,数字,布尔值和空值

      • 完整数据绑定意味着转换为任何Java bean类型(以及上面提到的简单类型) )

      • Simple data binding means converting to and from Java Maps, Lists, Strings, Numbers, Booleans and nulls
      • Full data binding means converting to and from any Java bean type (as well as "simple" types mentioned above)

      通常使用树模型方法被认为是最好的,因为它提供了遍历树的优势。

      Typically using "Tree Model" approach is considered as best from "performance perspective" because it gives advantages of traversing a tree.

      其他选项也有自己的优势,如 Streaming API具有更少的内存和CPU开销,而数据绑定使用方便,因为它提供 List Map JSON数据的表示。然而,由于具有如此强大的处理能力和内存,现在真正重要的是性能。

      Other options has also its own advantages like Streaming API has less memory and CPU overhead while Data binding is convenient to use because it provides List and Map representation of JSON data. However, with so much processing power and memory, these days what really matters is performance.

      如果您的JSON数据很大,那么在树表示中分析树是否会宽度更宽或长度更长。如果它具有更宽的宽度,那么明确使用树模型将具有与树处理相关联的性能优势(确保您以块为单位进行映射而不是一次性完成整个)。但是如果树更长,意思是没有好的宽度但是就像一条很长的尾巴,那么考虑使用Streaming API,因为在这种情况下,树处理的优点无法得到证实。如果数据很小,则几乎不重要,您可以使用树模型作为默认值。

      If your JSON data is huge and then analyze that in a tree representation whether tree would have wider width or longer length. If it has wider width then definitely using "Tree Model" will have performance advantages associated with a tree processing (make sure you are mapping in chunks and not whole stuff in one shot). But if tree is lengthier, meaning doesn't have good width but is like a very long tail, then consider using "Streaming API" because in that case advantages of tree processing cannot be substantiated. If data is small then it hardly matters and you can use "Tree Model" as default.

      目前您正在使用数据绑定方法,但建议使用树模型,因为您需要的只是遍历和操纵JSON 。查看您提供的信息,看起来您不需要将JSON转换为Java对象,因此数据绑定方法看起来不错。

      Currently you are using "Data Binding" approach but recommendation is to use "Tree Model" because all you need is traversal and manipulation of JSON. Looking at information you have given, it doesn't look like you need to convert your JSON into Java objects so "data binding" approach looks like a bad idea.

      Jackson的 com.fasterxml.jackson.databind.JsonNode 构成了杰克逊树模型的基础。 将Jackson的Tree模型视为HTML文档的DOM, DOM表示树结构中的完整HTML文档的方式,Jackson的Tree模型表示树形结构中的完整JSON字符串。

      Jackson's com.fasterxml.jackson.databind.JsonNode forms the basis of Jackson's tree model. Think of Jackson's Tree model as a DOM of HTML document, the way DOM represents complete HTML document in a tree structure, Jackson's Tree model represent complete JSON string in a tree strcuture.

      以下代码将帮助您使用杰克逊树模型并实现您的目标:

      Below is the code which will help you use Jackson's Tree model and achieve what you are looking for:

      import java.io.IOException;
      import java.util.Iterator;
      
      import com.fasterxml.jackson.core.JsonProcessingException;
      import com.fasterxml.jackson.databind.JsonNode;
      import com.fasterxml.jackson.databind.ObjectMapper;
      import com.fasterxml.jackson.databind.node.ObjectNode;
      
      
      public class Test {
      
          public static void main(String[] args) throws JsonProcessingException, IOException {
              String jsonString = "{\"test1\": {\"get\": {\"tags\": [\"restcalls1\"]}}, \"test2\": {\"put\": {\"tags\": [\"restcalls2\"] }}}";
              ObjectMapper objectMapper = new ObjectMapper();
              JsonNode rootNode = objectMapper.readTree(jsonString);
      
              Iterator<JsonNode> iterator2 = rootNode.iterator();
              while (iterator2.hasNext()) {
                  JsonNode node2 = iterator2.next().findParent("tags");
                  ObjectNode objectNode = (ObjectNode) node2;
                  objectNode.putArray("tags").add("my rest calls");
              }
      
              Iterator<JsonNode> iterator = rootNode.iterator();
              while (iterator.hasNext()) {
                  JsonNode node2 = iterator.next();
                  System.out.println(node2);
              }
      
          }
      }
      

      树模型优势:

      阅读此处了解更多信息详细信息

      Tree model advantages:

      Read here for more details


      • 如果Json内容的结构非常不规则,则可能很难(或不可能)找到或创建等效的Java对象结构。树模型可能是唯一可行的选择。

      • 用于显示任何JSON内容。 树模型是内部访问和操作的自然选择。

      • 由于我们不需要绑定特定的Java对象,因此编写的代码可能更少。 / li>
      • If the structure of Json content is highly irregular, it may be difficult (or impossible) to find or create equivalent Java object structure. Tree model may be the only practical choice.
      • For displaying any JSON content. Tree model is a natural choice for internal access and manipulation.
      • Since we do not need specific Java objects to bind to, there may less code to write.

      进一步阅读:

      • There are Three -- and Only Three -- Ways to Process Json
      • Traversing JSON trees with Jackson
      • Json processing with Jackson



      基于OP的评论:


      Based on OP's comment:

      下面的代码显示了如何遍历和打印整个JSON。通过这种方式,您可以遍历整个JSON,然后访问您要查找的元素。要注意的是,您需要知道元素名称,即使您使用Stream API方法,您也应该知道要查找的元素名称,请参阅Stream API示例这里

      Below code shows how you can traverse and print whole JSON. In this way, you can traverse whole JSON and then access elements you are looking for. Key think to note is that you need to know the element name, even if you use Stream API approach then also you should know the element name to look for, see Stream API example here

      在任何情况下,您始终可以选择遍历整个JSON(如下面的示例所示)或进行特定和直接操作(如上例所示)

      package com.him.services;
      
      import java.io.IOException;
      import java.util.ArrayList;
      import java.util.Iterator;
      
      import com.fasterxml.jackson.core.JsonProcessingException;
      import com.fasterxml.jackson.databind.JsonNode;
      import com.fasterxml.jackson.databind.ObjectMapper;
      
      
      public class Test {
      
          public static void main(String[] args) throws JsonProcessingException, IOException {
              jacksonTest();
          }
      
          private static void jacksonTest() throws JsonProcessingException, IOException {
              String jsonString = "{\"test1\": {\"get\": {\"tags\": [\"restcalls1\"]}}, \"test2\": {\"put\": {\"tags\": [\"restcalls2\"] }}}";
              ObjectMapper objectMapper = new ObjectMapper();
              JsonNode rootNode = objectMapper.readTree(jsonString);
              ArrayList<JsonNode> nodeList = new ArrayList<JsonNode>();
              nodeList.add(rootNode);
      
              printCompleteJson(nodeList);
          }
      
          private static void printCompleteJson(ArrayList<JsonNode> rootNode) throws IOException {
              for (int i = 0; i < rootNode.size(); i++) {
                  Iterator<JsonNode> iterator = rootNode.get(i).iterator();
                  JsonNode node = null;
                  ArrayList<JsonNode> nodeList = new ArrayList<JsonNode>();
                  boolean isEmpty = true;
                  while (iterator.hasNext()) {
                      isEmpty = false;
                      node = iterator.next();
                      nodeList.add(node);
                      System.out.println(node);
                  }
                  if(isEmpty){
                      return;
                  }
                  printCompleteJson(nodeList);
              }
          }
      }
      

      这篇关于从LinkedHashMap中检索值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆