我有以下java代码
@XmlRootElement
public class PreferenceEntity {
String type, name;
int id;
Map<String, String> attributes = new HashMap<String, String>();
List<PreferenceEntity> children;
PreferenceEntity parent;
public PreferenceEntity() {
parent = null;
}
public PreferenceEntity(PreferenceEntity parent) {
this.parent = parent;
}
@XmlAnyElement
public List<PreferenceEntity> getChildren() {
return children;
}
public void setChildren(List<PreferenceEntity> children) {
this.children = children;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
@JsonSerialize(contentUsing=SubjectAutocompleteSerializer.class)
public Map<String, String> getAttributes() {
return attributes;
}
@XmlTransient
public PreferenceEntity getParent() {
return parent;
}
public void setName(String name) {
this.name = name;
}
public void setId(int id) {
if (id >= 0) {
this.id = id;
}
}
// Internal class
public static class SubjectAutocompleteSerializer extends JsonSerializer<Map<String, String>> {
@Override
public void serialize(Map<String, String> map, JsonGenerator jgen, SerializerProvider provider)
throws IOException, JsonProcessingException {
jgen.writeStartObject();
for (String key:map.keySet()) {
jgen.writeStringField(key, map.get(key));
}
//jgen.writeFieldName(value.getType());
//jgen.writeStringField(value.getType(), value.getType());
// jgen.writeStartObject();
//jgen.writeObject(value);
//jgen.writeStartObject("XMY");
//jgen.writeStringField("value", value.getName());
// jgen.writeEndObject();
jgen.writeEndObject();
}
}
}
输出是:
{
-preferences : [
-{
-children : [
-{
children : null
type : "A1"
-attributes : {
ColumnId : "86"
}
}
-{
children : null
type : "A2"
-attributes : {
ColumnId : "87"
}
}
-{
children : null
type : "A1"
-attributes : {
ColumnId : "382"
Selected : "true"
}
}
所需的输出如下:
{
-preferences : [
-{
-children : [
-{
children : null
type : "A1"
ColumnId : "86"
}
-{
children : null
type : "A2"
ColumnId : "87"
}
-{
children : null
type : "A1"
ColumnId : "382"
Selected : "true"
}
}
如果我能得到它,那就更好了:
{
-preferences : [
-{
-A1 : [
-{
children : null
type : "A1"
ColumnId : "86"
}
-A2{
children : null
ColumnId : "87"
}
-A3{
children : null
ColumnId : "382"
Selected : "true"
}
}
我尝试使用 JsonSerialize,但它似乎不适用于 HashMap。任何指针都会有很大帮助。
问候白莲花