我正在尝试使用objectmapper序列化具有Map的java对象。 下面是我正在尝试并且已经起作用的代码。
public abstract class DataTypeModel {
DataType type;
String description;
public DataTypeModel(DataType type, String description) {
this.type = type;
this.description = description;
}
public DataType getType() {
return type;
}
public String getDescription() {
return description;
}
}
import lombok.Getter;
import lombok.Setter;
public class StringDataTypeModel extends DataTypeModel {
@Setter @Getter Integer minLength;
@Setter @Getter Integer maxLength;
public StringDataTypeModel(DataType type, String description, Integer minLength, Integer maxLength) {
super(type, description);
this.minLength = minLength;
this.maxLength = maxLength;
}
}
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import lombok.Data;
@Data
public class TableModel {
private String type;
private List<String> required = new ArrayList<String>();
private Map<String, DataTypeModel> properties = new LinkedHashMap<>();
private String title;
private String name;
}
public class Test {
public static void main(String args[]) throws IOException {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
mapper.writerWithDefaultPrettyPrinter();
TableModel table = new TableModel();
Map<String, DataTypeModel> properties = new HashMap<>();
properties.put("code", new StringDataTypeModel(DataType.string, "this is string", 1, 15,"/s"));
properties.put("startDate", new DateDataTypeModel(DataType.date, "this is date", "pattern"));
table.setProperties(properties);
table.setType("object");
table.setRequired(Arrays.asList("code"));
table.setTitle("this is branch table for bank");
mapper.writer().withRootName("branch").writeValue(new File("Table.json"), table);
//Object to JSON in String
String jsonInString = mapper.writer().withRootName("branch").writeValueAsString(table);
System.out.println(jsonInString);
}
}
我能够产生预期的输出,即:
{
"type": "object",
"required": [
"a"
],
"properties": {
"a": {
"type": "number",
"description": "this is column a"
},
"b": {
"type": "date",
"description": "this is column b"
},
"fullName": {
"type": "string",
"description": "",
"minLength": 1,
"maxLength": 10
}
},
"title": "this is table",
"name": "test_table"
}
使用杰克逊对象映射器,我可以在字符串中生成预期的json。
最后,我序列化了具有Map对象的java对象,键是字符串,值是JSON字符串的抽象类