actolap / json-io

Automatically exported from code.google.com/p/json-io
0 stars 0 forks source link

class cast exception #3

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
        String  jsonString = "{\"name\": \"mybank\",\"address\": \"mybank address\"}";

        InputStream inputStream = new ByteArrayInputStream(jsonString.getBytes());

        JsonReader jr = new JsonReader(inputStream);
        Bank bank = (Bank) jr.readObject();

        System.out.println(bank.getName());
----------------------------------------------------------
when i use this code i got class cast exception  as following 
Exception in thread "main" java.lang.ClassCastException: java.lang.Object 
cannot be cast to com.test.Bank
    at com.test.TestJson.main(TestJson.java:22)

please help me in this

thank you

Original issue reported on code.google.com by haris2...@gmail.com on 5 Jul 2012 at 2:49

GoogleCodeExporter commented 9 years ago
I got the same cases.can you help me ?thank you in advance!

Original comment by huxiangy...@gmail.com on 10 Apr 2013 at 5:19

GoogleCodeExporter commented 9 years ago
This is not an error with json-io.  The JSON you have listed is not any Java 
object, because their is no '@type' tag in the JSON.  Try creating a Bank 
object and then writing one out like this:

Bank bank = new Bank();
String json = JsonWriter.toJson(bank);
System.out.println("bank in Json format");
System.out.println(json);

In order to be abe to cast it directly to an Java class, the JSON must include 
the '@type' tag, or the Json must be an array '[]' in which is can be cast to a 
Object[].

You can read this JSON String into memory like this:

String  jsonString = "{\"name\": \"mybank\",\"address\": \"mybank address\"}";
Map map = JsonReader.jsonToMaps(jsonString);

This this code, you will be able to read in ANY JSON String and then access any 
field of it, by drilling through the Maps.

Original comment by jdereg@gmail.com on 1 Jun 2013 at 8:47