Question

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

String json = "{\"email\":\"testing@example.com\",\"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...

Was it helpful?

Solution

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

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top