将Json字符串映射到Java中的map或hashmap字段 [英] Mapping Json string to map or hashmap field in java

查看:468
本文介绍了将Json字符串映射到Java中的map或hashmap字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我从服务器返回了以下JSON字符串:

Say I have the following JSON string returned from server:

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

在codehaus Jackson @JsonProperty中,如何从其中获取HashMap对象?

in codehaus Jackson @JsonProperty, how can I get a HashMap object out of it?

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) { }
    }
}

最后,我希望基于返回的JSON字符串生成的哈希映射为 (用Java伪语言编写)

At the end of the day, I want the hash map generated based on the returned JSON string to be (written in java pseudo)

如果我打电话给我,应该给我一个带有id=1url=ONE字段的Temp对象

should return me a Temp object with fields id=1 and url=ONE if I call

images.get("one")

如果我打电话给我,应该给我一个带有id=2url=TWO字段的Temp对象

should return me a Temp object with fields id=2 and url=TWO if I call

images.get("two") 

推荐答案

这应该可以按原样工作,但需要进行一些小的修改:您正在使用额外的响应"条目.因此,通常情况下,您可以使用包装器POJO,例如:

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:

class Wrapper {
  public MSShow response;
}

正确映射结构.或者,也可以使用UNWRAP_ROOT_VALUE功能(来自DeserializationConfig)自动执行此操作,尽管如果需要,则类名也必须匹配.

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.

,则结果确实为HashMap.如果不是,您还可以使用:

Result will indeed be a HashMap if the field type is that (which it is). If it wasn't you could also use:

@JsonDeserialize(as=HashMap.class)

强制使用特定的子类型.

to force specific subtype to be used.

这篇关于将Json字符串映射到Java中的map或hashmap字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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