类似于地图的序列化将数据值作为键

时间:2012-06-25 20:19:21

标签: java json serialization jackson

我需要序列化这个:

List<Event>

Event类是:

public class Event {
  public int id;
  public String foo;
  public String bar;
}

到这种形式的JSON:

{
  "123":{"foo":"...","bar":"..."},
  "345":{"foo":"...","bar":"..."}
}

将“id”属性从Event中删除并存储Map可以解决问题,但我需要支持重复的ID。

我可以在“id”属性上添加一个注释,使Jackson将其视为一个键,并将该对象的其余部分作为关联值吗?

2 个答案:

答案 0 :(得分:0)

以ID的当前结构为键,我不确定在JSON规范中是否可以有重复的ID。也许你有阵列ID。我认为你需要重新评估你想要的JSON输出。

答案 1 :(得分:0)

您可以使用IdentityHashMap,因此您可以使用包含相同值的字符串的不同实例并获得此结果:

{"1":{"foo":"foo1","bar":"bar"},"2":{"foo":"foo2.1","bar":"bar"},"3":{"foo":"foo2","bar":"baz"},"2":{"foo":"foo2","bar":"baz"}}

您可以执行此操作:

import java.io.IOException;
import java.util.Arrays;
import java.util.IdentityHashMap;
import java.util.List;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

public class JacksonTest {

    public static void main(final String[] args) throws JsonGenerationException, JsonMappingException, IOException {
        ObjectMapper om = new ObjectMapper();

        IdentityHashMap<String, Event> ihm = new IdentityHashMap<String, Event>();

        List<Event> list = Arrays.asList( //
                new Event(1, "foo1", "bar"), //
                new Event(2, "foo2", "baz"), //
                new Event(2, "foo2.1", "bar"), //
                new Event(3, "foo2", "baz") //
                );

        for (Event e : list) {
            ihm.put(String.valueOf(e.id), e);
        }

        System.out.println(om.writeValueAsString(ihm));
    }

    @JsonIgnoreProperties({ "id" })
    public static class Event {
        public int id;
        public String foo;
        public String bar;

        public Event(final int id, final String foo, final String bar) {
            super();
            this.id = id;
            this.foo = foo;
            this.bar = bar;
        }

    }

}