Java:从对象获取Map

huangapple go评论98阅读模式
英文:

Java: get Map from Object

问题

使用以下代码

    Map<String, Object> payloadMap = new HashMap<String, Object>();
    payloadMap = (Map<String, Object>) new Gson().fromJson(result, payloadMap.getClass());

我将这个 JSON 转换为一个具有**无限**数量的子映射的映射

{
"name":"name1",
"job":"prosecutor",
"department": {
"department_name":"prosecutor's office"
}
}


要获取子(嵌套)映射的值,我尝试从父映射的对象值中获取“包装”的子映射。

```java
public void mapRequestNode(Map<String, Object> payloadMap) {
   payloadMap.entrySet().forEach(node -> this.getDataFromNode(node));
}

如上图所示,无法使用被“包装”为对象的子映射“department”。我可以访问对象的方法,但无法访问映射的方法(例如,无法使用“value.get("department_name")”)。我尝试过转换为“(Map<String, Object>) value”,但没有成功...

上面的示例中,“department”名称只是举例说明!我不知道 JSON 子对象的具体名称。可能有无限数量的名称!因此我无法像这样使用“payloadMap.get("department")”


图片链接见原文。

<details>
<summary>英文:</summary>

Using this code

    Map&lt;String,Object&gt; payloadMap = new HashMap&lt;String,Object&gt;();
    payloadMap = (Map&lt;String,Object&gt;) new Gson().fromJson(result, payloadMap.getClass());

, I convert this json:

   {
      &quot;name&quot;:&quot;name1&quot;,
      &quot;job&quot;:&quot;prosecutor&quot;,
      &quot;department&quot;: {
                     &quot;department_name&quot;:&quot;prosecutor&#39;s office&quot;
                     }
    }

to the map (map with **unlimited** number of child maps):
[![enter image description here][1]][1]


This done well, but now I want to get an access to values of child (nested) maps.

In parent map child maps &quot;wrapped&quot; to Object.
So, I tried to get &quot;wrapped&quot; child maps from the Object-values of parent map.

      public void mapRequestNode (Map&lt;String,Object&gt; payloadMap) {
        payloadMap.entrySet().forEach(node-&gt;this.getDataFromNode(node));
      }
[![enter image description here][2]][2]

As you can see from the above picture, there are no way to use child map &quot;department&quot;, which had been &quot;wrapped&quot; to Object. I have an access to Object-methods, but not to the Map-methods (for example, I cant use &quot;value.get(&quot;department_name&quot;)&quot;. I tried cast &quot;(Map&lt;String, Object&gt;)value&quot;, but without success...


The &quot;department&quot; name in case above is only for example!  I dont know concrete name of json child-objects. There may be **unlimited** number of names! So I cant use something like this &quot;payloadMap.get(&quot;department&quot;)&quot; 

  [1]: https://i.stack.imgur.com/5V7co.png
  [2]: https://i.stack.imgur.com/b3rDQ.png

</details>


# 答案1
**得分**: 1

以下是翻译好的内容:

接下来

((Map<String, Object>) payloadMap.get("department")).get("department_name")

应该可以工作,对吧?


<details>
<summary>英文:</summary>

Following

    ((Map&lt;String, Object&gt;)payloadMap.get(&quot;department&quot;)).get(&quot;department_name&quot;)

should work, dont?

</details>



# 答案2
**得分**: 1

你的变量 `value` 的类型是 Object,这意味着编译器不会了解关于这个变量的其他信息。即使你从 JSON 文件中检索到的对象是一个映射(map),由于你将其存储在一个 Object 变量中,编译器会将其处理为 Object 而不是 Map。这就是为什么你不能执行 `value.get("department");`:对于 Object 类型,不存在 `get` 方法。

你需要将存储在 `value.get("department")` 中的内容强制转换为 `Map<String, Object>`,以便能够将其处理为一个映射(Map)。

<details>
<summary>英文:</summary>

Your variable `value` is of type Object, which means that the compiler will not know anything else about the variable. Even if the object you retrieve from your json file is a map, as you store it in a Object variable, the compiler will handle it as an Object and not as a Map. That is why you cannot do `value.get(&quot;department&quot;);` : the method `get` does not exist for the type Object. 

You need to cast whatever is stored in `value.get(&quot;department&quot;)` as a `Map&lt;String, Object&gt;` to be able to handle it as a Map.

</details>



# 答案3
**得分**: 0

我已经找到了一个特殊的解决方案。

我将json转换为Map&lt;String,Map&lt;String,Object&gt;&gt;。
不是Map&lt;String,Object&gt;。在这种情况下,我可以成功地使用父DTO映射的子映射。

但这个解决方案在意义上是特殊的(不是通用的),因为我可以以这种方式处理仅由对象组成的json。

例如,如果我尝试在以下示例中获取&quot;job&quot;的值:

    {
       &quot;job&quot;: &quot;prosecutor&quot;,
      &quot;department&quot;: {
                     &quot;department_name&quot;:&quot;prosecutor&#39;s office&quot;
                     }
    }  

通过使用Map.Entry&lt;String, Map&lt;String, Object&gt;&gt; payloadNodeEntry.getValue,
我将收到ClassCastException(无法将String转换为Map&lt;String, Object&gt;)。


<details>
<summary>英文:</summary>

I have found a special solution.

I convert json to Map&lt;String,Map&lt;String,Object&gt;&gt;.
Not in Map&lt;String,Object&gt;. In this case I can successfully use child-maps of parent dto-map.

But this solution is special (not general) in the meaning that, I can handle in this way json, which consist only of objects.

For example, if I try to get the value of &quot;job&quot; in following example:

    {
       &quot;job&quot;: &quot;prosecutor&quot;,
      &quot;department&quot;: {
                     &quot;department_name&quot;:&quot;prosecutor&#39;s office&quot;
                     }
    }  

by using Map.Entry&lt;String, Map&lt;String, Object&gt;&gt; payloadNodeEntry.getValue,
I will receive ClassCastException (cant cast String to Map&lt;String, Object&gt; ).
 

</details>



huangapple
  • 本文由 发表于 2020年9月28日 00:38:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/64090861.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定