Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic object serialization in Jackson with Java

Tags:

java

json

jackson

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()); 
    }
    }

}
like image 255
edd Avatar asked Feb 14 '11 16:02

edd


People also ask

Does Jackson use Java serialization?

Note that Jackson does not use java. io. Serializable for anything: there is no real value for adding that. It gets ignored.

Why do we use ObjectMapper in Java?

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.


1 Answers

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.

like image 105
oconnor0 Avatar answered Nov 01 '22 17:11

oconnor0