alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

Jetty example source code file (JSONEnumConvertor.java)

This example Jetty source code file (JSONEnumConvertor.java) is included in the DevDaily.com "Java Source Code Warehouse" project. The intent of this project is to help you "Learn Java by Example" TM.

Java - Jetty tags/keywords

class, class, enums, jsonenumconvertor, jsonenumconvertor, method, object, object, output, reflection, runtimeexception, unsupportedoperationexception, unsupportedoperationexception, util

The Jetty JSONEnumConvertor.java source code

package org.mortbay.util.ajax;

import java.lang.reflect.Method;
import java.util.Map;

import org.mortbay.log.Log;
import org.mortbay.util.Loader;
import org.mortbay.util.ajax.JSON.Output;

/* ------------------------------------------------------------ */
/**
 * Convert an {@link Enum} to JSON.
 * If fromJSON is true in the constructor, the JSON generated will
 * be of the form {class="com.acme.TrafficLight",value="Green"}
 * If fromJSON is false, then only the string value of the enum is generated.
 * @author gregw
 *
 */
public class JSONEnumConvertor implements JSON.Convertor
{
    private boolean _fromJSON;
    private Method _valueOf;
    {
        try
        {
            Class e = Loader.loadClass(getClass(),"java.lang.Enum");
            _valueOf=e.getMethod("valueOf",new Class[]{Class.class,String.class});
        }
        catch(Exception e)
        {
            throw new RuntimeException("!Enums",e);
        }
    }

    public JSONEnumConvertor()
    {
        this(false);
    }
    
    public JSONEnumConvertor(boolean fromJSON)
    {
        _fromJSON=fromJSON;
    }
    
    public Object fromJSON(Map map)
    {
        if (!_fromJSON)
            throw new UnsupportedOperationException();
        try
        {
            Class c=Loader.loadClass(getClass(),(String)map.get("class"));
            return _valueOf.invoke(null,new Object[]{c,map.get("value")});
        }
        catch(Exception e)
        {
            Log.warn(e);  
        }
        return null;
    }

    public void toJSON(Object obj, Output out)
    {
        if (_fromJSON)
        {
            out.addClass(obj.getClass());
            out.add("value",obj.toString());
        }
        else
        {
            out.add(obj.toString());
        }
    }

}

Other Jetty examples (source code examples)

Here is a short list of links related to this Jetty JSONEnumConvertor.java source code file:

... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2021 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.