如何为json String生成pojo类

时间:2012-12-07 06:12:48

标签: json rest mapping jackson pojo

我有一个json String

{
"user": [
    {
        "actor": "ashok"
    },
    {
        "actor": {
            "name": "ashok",
            "mail": "ashok@gmail.com"
        }
    },
    {
        "actor": [
            "ashok",
            "kumar"
        ]
    }
]
}

如何生成POJO类。这是为了让jackson mapper自动映射bean类中的以下json。

1 个答案:

答案 0 :(得分:1)

public class MainBean
{
   private List<UserBean> user = new ArrayList<UserBean>();

   // getter/ setter
}  

public class UserBean 
{
   private String actor; // this for "actor": "ashok" 

   private Map<String, String> actorMap; // this for second case

   private List<String> actors; // this for third case

   @JsonAnySetter
   public void set(String name, Object value)
   {
      if (value instanceof String)
      {
         actor = (String) value;   
      }
      else if (value instanceof Map)
      {
         actorMap = (Map<String, String>) value;   
      }
      else if (value instanceof List)
      {
         actors =  (List<String>) value; 
      }
   }
}  

是第二种情况,您可以创建包含两个字符串字段namemail的简单类,并在if (value instanceof Map)

之后在其上创建新实例