简体   繁体   English

将Json字符串映射到java中的map或hashmap字段

[英]Mapping Json string to map or hashmap field in java

Say I have the following JSON string returned from server:假设我从服务器返回了以下 JSON 字符串:

{
    "response":{
        "imageInstances":{
            "one":{
                "id":"1",
                "url":"ONE"
            },         
            "two":{
                "id":"2",
                "url":"TWO"
            }
        }
    }  
}

in codehaus Jackson @JsonProperty , how can I get a HashMap object out of it?在 codehaus Jackson @JsonProperty ,如何从中获取HashMap对象?

import org.codehaus.jackson.annotate.JsonAnySetter;
import org.codehaus.jackson.annotate.JsonProperty;

import java.util.HashMap;
import java.util.List;

public class MSShow {
  @JsonProperty("imageInstances") private HashMap<String, Temp> images;//// HOW DO YOU CONVERT IT TO HASH MAP??????
  @JsonAnySetter public void ignoredField(String key, Object value) { }

  private class Temp {
    @JsonProperty("id") private String id;
    @JsonProperty("url") private String url;
    @JsonAnySetter public void ignoredField(String key, Object value) { }
    }
}

At the end of the day, I want the hash map generated based on the returned JSON string to be (written in java pseudo)归根结底,我希望根据返回的 JSON 字符串生成哈希映射(用 java 伪代码编写)

should return me a Temp object with fields id=1 and url=ONE if I call如果我打电话,应该返回一个带有字段id=1url=ONE的 Temp 对象

images.get("one")

should return me a Temp object with fields id=2 and url=TWO if I call如果我打电话,应该返回一个带有字段id=2url=TWO的 Temp 对象

images.get("two") 

That should work as is, with one small modification: you are using extra "response" entry.这应该可以正常工作,只需稍作修改:您正在使用额外的“响应”条目。 So typically you would either use a wrapper POJO like:所以通常你会使用一个包装器 POJO,如:

class Wrapper {
  public MSShow response;
}

to map structure properly.正确映射结构。 Or you can use UNWRAP_ROOT_VALUE Feature (from DeserializationConfig ) to do this automatically, although name of the class needs to match if so.或者您可以使用UNWRAP_ROOT_VALUE功能(来自DeserializationConfig )自动执行此操作,尽管如果是这样,类的名称需要匹配。

Result will indeed be a HashMap if the field type is that (which it is).如果字段类型是那个(它是),那么结果确实是一个HashMap If it wasn't you could also use:如果不是,您还可以使用:

@JsonDeserialize(as=HashMap.class)

to force specific subtype to be used.强制使用特定的子类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM