Menu

Partial Enum support?

Help
IRedfield
2007-03-25
2013-04-29
  • IRedfield

    IRedfield - 2007-03-25

    Hi
    I use json-lib-1.0-jdk15 and class with enum property:
    class MyBean{
      private JEnum jEnum;
    ...
    }

    enum JEnum{
      VAL_1, VAL_2
    }

    When I call
      JSONObject.fromBean(new MyBean()).toString();
    I get {"JEnum":"VAL_1"} string, thats seems to be ok.

    But, when I try to convert this string back to MyBean calling next line
      JSONObject.toBean(JSONObject.fromString("{\"JEnum\":\"VAL_1\"}"), MyBean);
    I get java.lang.IllegalArgumentException: Cannot invoke MyBean.setJEnum - argument type mismatch
    There is any solution for this problem?
    Thanks

     
    • aalmiray

      aalmiray - 2007-03-25

      IRedfield,

      It does work but the configuration is not as you would expect, try the following

            JSONUtils.getMorpherRegistry()
                  .registerMorpher( new EnumMorpher( JsonEnum.class ) );
            JSONObject json = new JSONObject();
            json.put( "jsonEnum", "OBJECT" );
            EnumBean bean = (EnumBean) JSONObject.toBean( json, EnumBean.class );
            assertNotNull( bean );
            assertEquals( bean.getJsonEnum(), JsonEnum.OBJECT )

      You have to register an EnumMorpher that wraps the target Enum, don't worry
      you can wrap and register as many target Enums as needed.
      I see now that this is not intuitive and I think an explanation is missing on
      the page. Also this may change in a future major release, as the type handling
      mechanism is being reworked form scratch to support custom serialization.

      Hope this helps you.

      -- Andres

       

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.