Menu

JSON to Java and interfaces

Help
2009-01-27
2013-04-29
  • Jake Goldman

    Jake Goldman - 2009-01-27

    Hello,

    Very happy with JSON-lib, it's a fantastic library that made my life a lot easier, thank you to authors and contributors! A few questions:

    My object model:

    interface Shape() {
      String getName();
      void setName(String s);
    }

    class Rectangle implements Shape {
       private name = "rectangle"; // returned by getName, setName defaults to that
       draw() {..}
    }

    class Circle implements Shape {
      private name = "circle"; // returned by getName, setName defaults to that
      draw() {...}
    }

    class Palette {
      List<Shape> shapes;
    }

    1. When doing JSONSerializer.toJava with rootClass set to Palette, I get
    "beanClass is an interface exception" for Shape. How do I tell json-lib that if it sees a Shape with "name" = "rectangle" to instantiate class Rectangle? I am open to modifying my object model, using DynaBeans, etc.

    2. When serializing Palette to JSON, I'd like the following JSON:

    {
      "shape1":   {
         "name" = "circle"
         "someProp" = "someVal"
      },
      "shape2" : {
         "name" = "circle"
         "someProp" = "someVal"
      }
    }

    I am not sure what method signatures need to be present on Palette but I don't think I can do it with a straight bean. Do I implement DynaBean then or use one of the provided DynaBean implementations to wrap Palette?

     
    • aalmiray

      aalmiray - 2009-01-28

      Hi Jake,

      For issue #1 you can set a custom NewBeanInstanceStrategy via JsonConfig.setNewBeanInstanceStrategy(). You will receive a Class and the current JSONObject being processed, then you can make a choice based on the that objetc's properties (like name = "rectangle").

      For issue #2 it seems that you'd like to turn an array into an object where each element follows a naming convention. Perhaps a JsonBeanProcessor will help you here, as outlined in tip #4 at http://jroller.com/aalmiray/entry/json_lib_hibernate_tips_and

      Cheers,
      Andres

       

Log in to post a comment.