Skip to content

Commit 644487b

Browse files
committed
Fix #1255
1 parent d15b19f commit 644487b

File tree

2 files changed

+47
-2
lines changed

2 files changed

+47
-2
lines changed

src/main/java/com/fasterxml/jackson/databind/ser/impl/WritableObjectId.java

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,10 @@ public final class WritableObjectId
1919

2020
public Object id;
2121

22+
/**
23+
* Marker to denote whether Object Id value has been written as part of an Object,
24+
* to be referencible. Remains false when forward-reference is written.
25+
*/
2226
protected boolean idWritten = false;
2327

2428
public WritableObjectId(ObjectIdGenerator<?> generator) {
@@ -27,7 +31,7 @@ public WritableObjectId(ObjectIdGenerator<?> generator) {
2731

2832
public boolean writeAsId(JsonGenerator gen, SerializerProvider provider, ObjectIdWriter w) throws IOException
2933
{
30-
if (id != null && (idWritten || w.alwaysAsId)) {
34+
if ((id != null) && (idWritten || w.alwaysAsId)) {
3135
// 03-Aug-2013, tatu: Prefer Native Object Ids if available
3236
if (gen.canWriteObjectId()) {
3337
gen.writeObjectRef(String.valueOf(id));
@@ -40,7 +44,13 @@ public boolean writeAsId(JsonGenerator gen, SerializerProvider provider, ObjectI
4044
}
4145

4246
public Object generateId(Object forPojo) {
43-
return (id = generator.generateId(forPojo));
47+
// 04-Jun-2016, tatu: As per [databind#1255], need to consider possibility of
48+
// id being generated for "alwaysAsId", but not being written as POJO; regardless,
49+
// need to use existing id if there is one:
50+
if (id == null) {
51+
id = generator.generateId(forPojo);
52+
}
53+
return id;
4454
}
4555

4656
/**
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package com.fasterxml.jackson.databind.objectid;
2+
3+
import com.fasterxml.jackson.annotation.*;
4+
import com.fasterxml.jackson.databind.*;
5+
6+
public class AlwaysAsReferenceFirstTest extends BaseMapTest
7+
{
8+
@JsonPropertyOrder({ "bar1", "bar2" })
9+
static class Foo {
10+
11+
@JsonIdentityReference(alwaysAsId = true)
12+
public Bar bar1;
13+
14+
@JsonIdentityReference
15+
public Bar bar2;
16+
}
17+
18+
@JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class)
19+
static class Bar {
20+
public int value = 3;
21+
}
22+
23+
public void testIssue1255() throws Exception
24+
{
25+
ObjectMapper mapper = new ObjectMapper();
26+
Foo mo = new Foo();
27+
mo.bar1 = new Bar();
28+
mo.bar2 = mo.bar1;
29+
30+
String json = mapper.writeValueAsString(mo);
31+
32+
Foo result = mapper.readValue(json, Foo.class);
33+
assertNotNull(result);
34+
}
35+
}

0 commit comments

Comments
 (0)