Skip to content

Commit cd59508

Browse files
committed
Improvement wrt #333
1 parent 2322ce6 commit cd59508

File tree

2 files changed

+41
-4
lines changed

2 files changed

+41
-4
lines changed

src/main/java/com/fasterxml/jackson/databind/node/JsonNodeFactory.java

+26-4
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ public static JsonNodeFactory withExactBigDecimals(boolean bigDecimalExact)
8383
{
8484
return bigDecimalExact ? decimalsAsIs : decimalsNormalized;
8585
}
86-
86+
8787
/*
8888
/**********************************************************
8989
/* Factory methods for literal values
@@ -171,16 +171,25 @@ public ValueNode numberNode(Integer value) {
171171
* that expresses given 64-bit integer value
172172
*/
173173
@Override
174-
public NumericNode numberNode(long v) { return LongNode.valueOf(v); }
175-
174+
public NumericNode numberNode(long v) {
175+
if (_inIntRange(v)) {
176+
return IntNode.valueOf((int) v);
177+
}
178+
return LongNode.valueOf(v);
179+
}
180+
176181
/**
177182
* Alternate factory method that will handle wrapper value, which may be null.
178183
* Due to possibility of null, returning type is not guaranteed to be
179184
* {@link NumericNode}, but just {@link ValueNode}.
180185
*/
181186
@Override
182187
public ValueNode numberNode(Long value) {
183-
return (value == null) ? nullNode() : LongNode.valueOf(value.longValue());
188+
long l = value.longValue();
189+
if (_inIntRange(l)) {
190+
return IntNode.valueOf((int) l);
191+
}
192+
return (value == null) ? nullNode() : LongNode.valueOf(l);
184193
}
185194

186195
/**
@@ -322,5 +331,18 @@ public BinaryNode binaryNode(byte[] data, int offset, int length) {
322331
*/
323332
@Deprecated
324333
public POJONode POJONode(Object pojo) { return new POJONode(pojo); }
334+
335+
/*
336+
/**********************************************************
337+
/* Helper methods
338+
/**********************************************************
339+
*/
340+
341+
protected boolean _inIntRange(long l)
342+
{
343+
int i = (int) l;
344+
long l2 = (long) i;
345+
return (l2 == l);
346+
}
325347
}
326348

src/test/java/com/fasterxml/jackson/databind/node/TestNumberNodes.java

+15
Original file line numberDiff line numberDiff line change
@@ -241,4 +241,19 @@ public void testBigDecimalAsPlain() throws Exception
241241
// also via ObjectWriter:
242242
assertEquals("{\"x\":100}", mapper.writer().writeValueAsString(node));
243243
}
244+
245+
// Related to [Issue#333]
246+
public void testCanonicalNumbers() throws Exception
247+
{
248+
JsonNodeFactory f = new JsonNodeFactory();
249+
NumericNode n = f.numberNode(123);
250+
assertTrue(n.isInt());
251+
n = f.numberNode(1L + Integer.MAX_VALUE);
252+
assertFalse(n.isInt());
253+
assertTrue(n.isLong());
254+
// but "too small" number will be 'int'...
255+
n = f.numberNode(123L);
256+
assertTrue(n.isInt());
257+
assertFalse(n.isLong());
258+
}
244259
}

0 commit comments

Comments
 (0)