0

I have Tag.java:

public class Tag{
  private List<Tag> links;
}

now A,B,C entities, A link B (means B link A),C; B link A,C, C link A,B

How can I make json serialize first level links?

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
Dreampie
  • 1,321
  • 4
  • 17
  • 32

1 Answers1

0

I was able to achieve the solution through Jackson's custom serializer

I added a name to identify Tag instances, and an annotation that specifies serializer class:

@JsonSerialize(using = TagJsonSerializer.class)
public class Tag
{
    public String name;
    public List<Tag> links = new ArrayList<>();
}

Below is the serializer. under "links" it writes the names of the tags, thus avoiding circular reference:

public class TagJsonSerializer extends JsonSerializer<Tag>
{
    @Override
    public void serialize(Tag value, JsonGenerator jgen, SerializerProvider provider)
            throws IOException, JsonProcessingException
    {
        try {
            jgen.writeStartObject();
            jgen.writeFieldName("name");
            jgen.writeObject(value.name);
            jgen.writeFieldName("links");
            Object[] tagNames = value.links.stream().map(tag -> tag.name)
                    .collect(Collectors.toList()).toArray();
            jgen.writeObject(tagNames);
            jgen.writeEndObject();
            return;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

Test method:

public static void main(String... args)
{
    Tag a = new Tag();
    Tag b = new Tag();
    Tag c = new Tag();
    a.name = "A";
    a.links.add(b);
    a.links.add(c);
    b.name = "B";
    b.links.add(a);
    b.links.add(c);
    c.name = "C";
    c.links.add(a);
    c.links.add(b);

    ObjectMapper mapper = new ObjectMapper();
    try {
        mapper.writeValue(System.out, a);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

Output:

{"name":"A","links":["B","C"]}
Sharon Ben Asher
  • 13,849
  • 5
  • 33
  • 47