从map(它的字段)中提取值并将其写入JSON

时间:2018-03-19 12:14:15

标签: java json objectmapper

使用ObjectMapper中的com.fasterxml.jackson.databind是否可以从地图中提取值并将其写入JSON?没有地图的额外标签?

例如我们有课程:

public class LoginInfoJSON {
    private Map<String, Object> properties = new HashMap<>();
    private String username;
    private String password;

    //getters and setters + constructor
}

如果我们尝试将其转换为JSON,那么它将是:

{
  "properties":
     {
      "numberTest":22,
      "array":["John","Anna","Peter"],
      "nullTest":null,
      "booleanTest":true,
      "employee":{"name":"John","age":30,"city":"New York"},
      "stringTest":"String"
      },
   "username":"pwe",
   "password":"pwe"
}

但是可以这样做吗?

{
    "numberTest":22,
    "array":["John","Anna","Peter"],
    "nullTest":null,
    "booleanTest":true,
    "employee":{"name":"John","age":30,"city":"New York"},
    "stringTest":"String",
    "username":"pwe",
    "password":"pwe"
}

可能有些注释可以处理吗?

有人可以提出建议吗?

修改

正如所建议的那样 - 我应该编写自己的序列化程序,

但我现在面临的问题是: 所以这是我的serizlizer:

public class ItemSerializer extends JsonSerializer<Map<String, Object>> {

    @Override
    public void serialize(Map<String,Object> map, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        Annotation[] mapAnnotations = map.getClass().getAnnotations();
        for(int i = 0; i < mapAnnotations.length; i++){
            if(mapAnnotations[i].getClass().isInstance(MapPropertiesAnnotation.class)){
                jsonGenerator.writeStartObject();
                for(Map.Entry<String, Object> mapEntry : map.entrySet()){
                    jsonGenerator.writeObjectField(mapEntry.getKey(), mapEntry.getValue());
                }
                jsonGenerator.writeEndObject();
            }
        }
    }
}

然后我将此作为模块添加到ObjectMapper

public class MapModule extends SimpleModule {
    public MapModule() {
        addSerializer(Map.class, new ItemSerializer());
    }
}

在maven构建期间,我面临着错误:

error: method addSerializer in class SimpleModule cannot be applied to given types;

所以,我认为问题在于我正在尝试序列化(Map<String, Object>)而不只是Map

我应该如何宣布我的地图要序列化?

0 个答案:

没有答案