peter
peter

Reputation: 23

About jackson convert Java dataType

There's a project use Jackson, and have a Java object Data. In the object, there's a property, and it's also a object Raw. In this object,there's a property List<Object[]> e.g:

public class Data{
    Raw raw;
}

public class Raw{
    List<Object[]> list;
}

If the Object[] have a data type: long, and I give a value: 123, then the Jackson will convert this data type to int,

i.e: If the value's length < long && > int , the data type is also long, if length < int, the data type will become int.

I use the method:

 byte[] bytes = writeValueAsBytes(Data), Data data = readValue(bytes, Data.class)

How could I keep the original data type when it is converted?

Upvotes: 1

Views: 1552

Answers (2)

StaxMan
StaxMan

Reputation: 116522

You may want to use type of Number instead, so you can easily get values as whatever type you want. As others point out, JSON only has "integer number" type, and there is nothing in content to point out expected Java type. This means that your Class must indicate expected type; and if all you suggest is Object, it is free to choose the most efficient representation.

Upvotes: 0

Adam Gent
Adam Gent

Reputation: 49085

Jackson does what I think you want:

@Test
public void testJackson() throws Exception {
    List<Number> numbers = new ArrayList<Number>();
    numbers.add(100L);
    numbers.add(new Long(Integer.MAX_VALUE) + 1000L);
    numbers.add(10.0);
    ObjectMapper om = new ObjectMapper();
    System.out.println(om.writeValueAsString(numbers));
    List<Number> newNumbers = om.readValue(om.writeValueAsString(numbers), ArrayList.class);
    System.out.println(newNumbers);
    assertEquals(Integer.class, newNumbers.get(0).getClass());
    assertEquals(newNumbers.get(1).getClass(), Long.class);
    assertTrue(! numbers.equals(newNumbers) );
}

However numbers will not equal newNumbers because 100L should be an integer. The maximum number that JSON can handle is a 64 bit double precision.

If your doing data serialization like for binary images then I would encode the data in Base64.

Upvotes: 1

Related Questions