I would like to read in the string {"a": 1.0}
as a generic Java Object while keeping the same string format. However, when I try, Jackson automatically changes the internal representation to {a = 1}
. In other words, how can I get the following code to print {"a": 1.0}
instead of {a = 1}
? Note that, I have to read it in as an Object
(due to other program constraints).
import org.codehaus.jackson.map.ObjectMapper;
public class Main {
public static void main(String[] args) {
try
{
ObjectMapper mapper = new ObjectMapper();
Object myObject = mapper.readValue("{\"a\": 1.0}", Object.class);
System.out.println(myObject.toString());
}
catch (Exception e)
{
e.printStackTrace();
System.err.println(e.getMessage());
}
}
}
Note that Jackson does not use java. io. Serializable for anything: there is no real value for adding that. It gets ignored.
ObjectMapper provides functionality for reading and writing JSON, either to and from basic POJOs (Plain Old Java Objects), or to and from a general-purpose JSON Tree Model ( JsonNode ), as well as related functionality for performing conversions.
The created object will be a map (like the other comments) and so its toString
produces what you're seeing, {a = 1}
. To get your code to print something closer to your input value, you need to use Jackson to write it back out with something like:
System.out.println(mapper.writeValueAsString(myObject));
That gives me what I believe you're looking for:
{"a":1.0}
In other words, Jackson has deserialized your input string into an arbitrary Java object. When you call toString
on the object, its own toString
is, of course, used. This can write the object however it pleases, including using the method from Object
. To reproduce the input string, you have to use Jackson to serialize our object back out.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With