1 package com.fasterxml.jackson.databind.jsontype;
2 
3 import java.util.*;
4 
5 import com.fasterxml.jackson.annotation.*;
6 
7 import com.fasterxml.jackson.databind.*;
8 
9 // Test for [databind#1051], issue with combination of Type and Object ids,
10 // if (but only if) `JsonTypeInfo.As.WRAPPER_OBJECT` used.
11 public class WrapperObjectWithObjectIdTest extends BaseMapTest
12 {
13     @JsonRootName(value = "company")
14     static class Company {
15         public List<Computer> computers;
16 
Company()17         public Company() {
18             computers = new ArrayList<Computer>();
19         }
20 
addComputer(Computer computer)21         public Company addComputer(Computer computer) {
22             if (computers == null) {
23                 computers = new ArrayList<Computer>();
24             }
25             computers.add(computer);
26             return this;
27         }
28     }
29 
30     @JsonIdentityInfo(
31             generator = ObjectIdGenerators.PropertyGenerator.class,
32             property = "id"
33     )
34     @JsonTypeInfo(
35             use = JsonTypeInfo.Id.NAME,
36             include = JsonTypeInfo.As.WRAPPER_OBJECT,
37             property = "type"
38     )
39     @JsonSubTypes({
40             @JsonSubTypes.Type(value = DesktopComputer.class, name = "desktop"),
41             @JsonSubTypes.Type(value = LaptopComputer.class, name = "laptop")
42     })
43     static class Computer {
44         public String id;
45     }
46 
47     @JsonTypeName("desktop")
48     static class DesktopComputer extends Computer {
49         public String location;
50 
DesktopComputer()51         protected DesktopComputer() { }
DesktopComputer(String id, String loc)52         public DesktopComputer(String id, String loc) {
53             this.id = id;
54             location = loc;
55         }
56     }
57 
58     @JsonTypeName("laptop")
59     static class LaptopComputer extends Computer {
60         public String vendor;
61 
LaptopComputer()62         protected LaptopComputer() { }
LaptopComputer(String id, String v)63         public LaptopComputer(String id, String v) {
64             this.id = id;
65             vendor = v;
66         }
67     }
68 
testSimple()69     public void testSimple() throws Exception
70     {
71         Company comp = new Company();
72         comp.addComputer(new DesktopComputer("computer-1", "Bangkok"));
73         comp.addComputer(new DesktopComputer("computer-2", "Pattaya"));
74         comp.addComputer(new LaptopComputer("computer-3", "Apple"));
75 
76         final ObjectMapper mapper = new ObjectMapper();
77 
78         String json = mapper.writerWithDefaultPrettyPrinter()
79                 .writeValueAsString(comp);
80 
81         Company result = mapper.readValue(json, Company.class);
82         assertNotNull(result);
83         assertNotNull(result.computers);
84         assertEquals(3, result.computers.size());
85     }
86 }
87