jackson:将包含对象类的JSON转换为Map

时间:2011-12-06 13:40:18

标签: dictionary jackson

对象类:

class User{
    public String name;
    public String password;
}

JSON:

{ sc:"200", msg:"something", userInfo:{name:"n", password:"p"} }

我想得到这样的结果:

Map->contains 3 key-value
"sc"="200"
"msg"="something"
"userInfo"=User(Object Class)

我该怎么做?或者,我怎样才能让它使用另一个JAR工具包?

2 个答案:

答案 0 :(得分:8)

你必须选择是否需要“无类型”(地图,列表,包装),这很容易获得:

Map<String,Object> map = new ObjectMapper().readValue(json, Map.class);

或POJO。问题是,mapper真的不知道你想要“userInfo”映射到特定对象,而是将其他值映射到其他东西。

但我宁愿创建另一个类,例如:

public class Request {
   public int sc;
   public String message;
   public User userInfo;
   // and/or getters, setters, if you prefer
}

并绑定到:

Request req = new ObjectMapper().readValue(json, Request.class);

为什么在拥有真正的POJO时会弄乱不方便的地图,对吧? :)

答案 1 :(得分:3)

作为对StaxMan答案的略微修改,如果在某种程度上希望在地图中包含不是User对象的所有内容,杰克逊会提供@JsonAnySetter@JsonAnyGetter注释来获取任务完成。以下示例演示了如何使用它。

import java.util.HashMap;
import java.util.Map;

import org.codehaus.jackson.annotate.JsonAnySetter;
import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
import org.codehaus.jackson.annotate.JsonMethod;
import org.codehaus.jackson.map.ObjectMapper;

public class JacksonFoo
{
  public static void main(String[] args) throws Exception
  {
    // {"sc":"200","msg":"something","userInfo":{"name":"n","password":"p"}}
    String jsonInput = "{\"sc\":\"200\",\"msg\":\"something\",\"userInfo\":{\"name\":\"n\",\"password\":\"p\"}}";

    ObjectMapper mapper = new ObjectMapper().setVisibility(JsonMethod.FIELD, Visibility.ANY);

    Result result = mapper.readValue(jsonInput, Result.class);
    System.out.println(result);
    // output: 
    // Result: userInfo=User: name=n, password=p, otherThings={sc=200, msg=something}
  }
}

class Result
{
  Map otherThings = new HashMap();
  User userInfo;

  @JsonAnySetter
  void addThing(String key, Object value)
  {
    otherThings.put(key, value);
  }

  @Override
  public String toString()
  {
    return String.format("Result: userInfo=%s, otherThings=%s", userInfo, otherThings);
  }
}

class User
{
  String name;
  String password;

  @Override
  public String toString()
  {
    return String.format("User: name=%s, password=%s", name, password);
  }
}