Java can't deserialize JSON

3.5k views Asked by At

I'm getting an error trying to deserialize what I believe is a valid JSON string:

String json = "{\"email\":\"[email protected]\",\"password\":\"12345\"}";

// FlexJSON deserializer
JSONDeserializer<Signin> deserializer = new JSONDeserializer<Signin>();

// Deserialize into a Signin POJO.
Signin signin = deserializer.deserialize(json);

When I run this code, I get:

java.util.HashMap cannot be cast to com.myapp.server.Signin
java.lang.ClassCastException: java.util.HashMap cannot be cast to com.myapp.server.Signin
    at com.myapp.server.SigninService.doPost(SigninService.java:39)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    ... rest of stack trace omitted for brevity

Is my JSON malformed? It's almost as if the JSON is somehow "bad" and FlexJSON is treating it like a HashMap...

2

There are 2 answers

0
Mark Rotteveel On BEST ANSWER

Looking at the documentation, the problem is that your json doesn't declare its class. This means that you explicitly need to supply a Class object to the deserializer, as in Java generics are only compile time, not runtime.

To quote from the documentation:

We need to replace the type information we just dropped when we instantiate the deserializer. To do that we'll pass the class we want to use into to flexjson.JSONDeserializer.deserialize(String, Class) method like so:

Hero hero = new JSONDeserializer<Hero>().deserialize( jsonHarvey, Hero.class ); 

So use:

Signin signin = deserializer.deserialize(json, Signin.class);
4
peter.petrov On

This library you're using seems like it's not supported really.
Seems it's not changed since 2010. I would try using something else.

I have used this one for example without any issues.
http://code.google.com/p/google-gson/downloads/list