Java<->JSON and weird fields

how-to
Oct 14, 20102 mins

It’s pretty easy to do Java objects – JSON and vice versa transformations. There are lots of tools available, I personally prefer

Stringtree

. You can easily produce a valid JSON for a valid Java class with valid fields. But field name conventions are different between JSON and Java, and in some rare cases you stumble upon a field that doesn’t conform to the Java standard, e.g. with a dash in its name, something like ‘text-align’. This is the case when JavaBeans framework comes in handy. Frankly speaking it is not applied too often and is not known by modern programmers – it was a star in the late nineties. JavaBeans allows to declare a metadata for a Java bean. This declaration must be contained in an accompanying class with the same name as the bean itself but with BeanInfo appended. So if you have your bean named Abc the metadata class must be called AbcBeanInfo. Both of the classes must reside in the same package. Abc bean class may look something like this:


public class Abc {
  private String textAlign;
  public String getTextAlign() { return textAlign;}
  public void setTextAlign(String textAlign) { this.textAlign = textAlign; }
}

Once you convert it to JSON you will get something like this:


{"textAlign":"left"}

Now we’ll create an AbcBeanInfo right next to Abc:


public class AbcBeanInfo extends SimpleBeanInfo {
  public PropertyDescriptor[] getPropertyDescriptors() {
    try {
      return new PropertyDescriptor[]{
        new PropertyDescriptor("text-align", Abc.class, "getTextAlign", "setTextAlign")};
      } catch (IntrospectionException ex) {
        ex.printStackTrace();
        return null;
      }
   }
}

Trying to produce a JSON from it (at least with Stringtree) will give you the result that you need:


{"text-align":"left"}

Enjoy!