Jackson Json Type Mapping Inner Class [duplicate]

2019-01-18 02:55发布

I am trying to create the inner class type for an object being passed in as JSON but while I have read tons on here as well as Jackson's site I don't seem to be able to get the right combination so if anyone else has any pointers they would be much appreciated. I've posted some snippets below and removed all getters and setters, I didn't figure they needed posting. I'm using Jackson 2.2.

The classes I'm attempting to deserialize:

public class Settings {
  private int offset;
  private int limit;
  private String type;
  private Map<String, Criteria> criteria;

  public class Criteria {
    private String restriction;
    private Object value;
  }
}

The code I'm using to deserialize:

ObjectMapper om = new ObjectMapper();
TypeFactory tf = om.getTypeFactory();
JavaType map = tf.constructMapLikeType( Map.class, String.class, Criteria.class );
JavaType type = typeFactory.constructType( Settings.class, map );
Settings settings = om.readValue( entity, type );

My JSON testing data:

{ "type": "org.json.Car", "criteria": { "restriction": "eq", "value": "bmw" } }

2条回答
兄弟一词,经得起流年.
2楼-- · 2019-01-18 03:38

The correct answer is that you are missing the static keyword on the inner class.

Just make sure that the "static" keyword is there.

Read http://www.cowtowncoder.com/blog/archives/2010/08/entry_411.html

it takes you 3 minutes but make you happy for the rest of the day.

查看更多
一夜七次
3楼-- · 2019-01-18 03:39

If you can, then make your life simple and move the inner class to a normal class with a reference in the Settings class. And then do the marshalling using jackson, here is how you can have your classes:

public class Settings {
  private int offset;
  private int limit;
  private String type;
  private Map<String, Criteria> criteria;
  private Criteria criteria;
}


 class Criteria {
    private String restriction;
    private Object value;
  }
查看更多
登录 后发表回答