Skip to content

Commit ffe1ee4

Browse files
committed
ignore field when getter is available
1 parent 570ed8c commit ffe1ee4

File tree

2 files changed

+26
-14
lines changed

2 files changed

+26
-14
lines changed

src/main/java/com/jsoniter/spi/ClassDescriptor.java

Lines changed: 12 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -181,32 +181,30 @@ private static void decodingDeduplicate(ClassDescriptor desc) {
181181
}
182182
}
183183

184-
// TODO: do not remove, set toNames to []
185184
private static void encodingDeduplicate(ClassDescriptor desc) {
186-
HashMap<String, Binding> byName = new HashMap<String, Binding>();
185+
HashMap<String, Binding> byToName = new HashMap<String, Binding>();
186+
HashMap<String, Binding> byFieldName = new HashMap<String, Binding>();
187187
for (Binding field : desc.fields) {
188188
for (String toName : field.toNames) {
189-
if (byName.containsKey(toName)) {
189+
if (byToName.containsKey(toName)) {
190190
throw new JsonException("field encode to same name: " + toName);
191191
}
192-
byName.put(toName, field);
192+
byToName.put(toName, field);
193193
}
194+
byFieldName.put(field.name, field);
194195
}
195196
for (Binding getter : new ArrayList<Binding>(desc.getters)) {
197+
Binding existing = byFieldName.get(getter.name);
198+
if (existing != null) {
199+
existing.toNames = new String[0];
200+
}
196201
for (String toName : getter.toNames) {
197-
Binding existing = byName.get(toName);
202+
existing = byToName.get(toName);
198203
if (existing == null) {
199-
byName.put(toName, getter);
200-
continue;
201-
}
202-
if (desc.fields.remove(existing)) {
203-
continue;
204-
}
205-
if (existing.method != null && existing.method.getName().equals(getter.method.getName())) {
206-
// inherited interface getter
207-
desc.getters.remove(getter);
204+
byToName.put(toName, getter);
208205
continue;
209206
}
207+
existing.toNames = new String[0];
210208
throw new JsonException("field encode to same name: " + toName);
211209
}
212210
}

src/test/java/com/jsoniter/output/TestAnnotationJsonProperty.java

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,4 +36,18 @@ public void test_encoder() throws IOException {
3636
String output = JsonStream.serialize(obj);
3737
assertEquals("{\"field1\":\"100\"}", output);
3838
}
39+
40+
public static class TestObject3 {
41+
public String field1 = "hello";
42+
43+
@JsonProperty(to = {"field-1"})
44+
public String getField1() {
45+
return field1;
46+
}
47+
}
48+
49+
public void test_getter() throws IOException {
50+
String output = JsonStream.serialize(new TestObject3());
51+
assertEquals("{\"field-1\":\"hello\"}", output);
52+
}
3953
}

0 commit comments

Comments
 (0)