FileDocCategorySizeDatePackage
JSONParser.javaAPI DocGlassfish v2 API20521Fri May 04 22:37:00 BST 2007com.sun.grizzly.cometd.util

JSONParser

public class JSONParser extends Object
JSON Parser and Generator.

This class provides some static methods to convert POJOs to and from JSON notation. The mapping from JSON to java is:

object ==> Map
array ==> Object[]
number ==> Double or Long
string ==> String
null ==> null
bool ==> Boolean

The java to JSON mapping is:

String --> string
Number --> number
Map --> object
List --> array
Array --> array
null --> null
Boolean--> boolean
Object --> string (dubious!)

The interface {@link JSON.Generator} may be implemented by classes that know how to render themselves as JSON and the {@link #toString(Object)} method will use {@link JSON.Generator#addJSON(StringBuffer)} to generate the JSON. The class {@link JSON.Literal} may be used to hold pre-gnerated JSON object.

author
gregw

Fields Summary
Constructors Summary
private JSONParser()

Methods Summary
public static voidappend(java.lang.StringBuffer buffer, java.lang.Object object)
Append object as JSON to string buffer.

param
buffer
param
object

        if (object==null)
            buffer.append("null");
        else if (object instanceof Generator)
            appendJSON(buffer, (Generator)object);
        else if (object instanceof Map)
            appendMap(buffer, (Map)object);
        else if (object instanceof List)
            appendArray(buffer,((List)object).toArray());
        else if (object.getClass().isArray())
            appendArray(buffer,object);
        else if (object instanceof Number)
            appendNumber(buffer,(Number)object);
        else if (object instanceof Boolean)
            appendBoolean(buffer,(Boolean)object);
        else if (object instanceof String)
            appendString(buffer,(String)object);
        else
            // TODO - maybe some bean stuff?
            appendString(buffer,object.toString());
    
private static voidappendArray(java.lang.StringBuffer buffer, java.lang.Object array)

        if (array==null) {
            appendNull(buffer);
            return;
        }
        
        buffer.append('[");
        int length = Array.getLength(array);
        
        for (int i=0;i<length;i++) {
            if(i!=0)
                buffer.append(',");
            append(buffer,Array.get(array,i));
        }
        
        buffer.append(']");
    
private static voidappendBoolean(java.lang.StringBuffer buffer, java.lang.Boolean b)

        if (b==null) {
            appendNull(buffer);
            return;
        }
        buffer.append(b.booleanValue()?"true":"false");
    
private static voidappendJSON(java.lang.StringBuffer buffer, com.sun.grizzly.cometd.util.JSONParser$Generator generator)

        generator.addJSON(buffer);
    
private static voidappendMap(java.lang.StringBuffer buffer, java.util.Map object)

        if (object==null) {
            appendNull(buffer);
            return;
        }
        
        buffer.append('{");
        Iterator iter = object.entrySet().iterator();
        while(iter.hasNext()) {
            Map.Entry entry = (Map.Entry)iter.next();
            quote(buffer,entry.getKey().toString());
            buffer.append(':");
            append(buffer,entry.getValue());
            if (iter.hasNext())
                buffer.append(',");
        }
        
        buffer.append('}");
    
private static voidappendNull(java.lang.StringBuffer buffer)

        buffer.append("null");
    
private static voidappendNumber(java.lang.StringBuffer buffer, java.lang.Number number)

        if (number==null) {
            appendNull(buffer);
            return;
        }
        buffer.append(number);
    
private static voidappendString(java.lang.StringBuffer buffer, java.lang.String string)

        if (string==null) {
            appendNull(buffer);
            return;
        }
        
        quote(buffer,string);
    
private static voidcomplete(java.lang.String seek, com.sun.grizzly.cometd.util.JSONParser$Source source)

        int i=0;
        while(source.hasNext()&& i<seek.length()) {
            char c=source.next();
            if(c!=seek.charAt(i++))
                throw new IllegalStateException("Unexpected '"+c+" while seeking  \""+seek+"\"");
        }
        
        if (i<seek.length())
            throw new IllegalStateException("Expected \""+seek+"\"");
    
public static byteconvertHexDigit(byte b)

param
b An ASCII encoded character 0-9 a-f A-F
return
The byte value of the character 0-16.

        if ((b >= '0") && (b <= '9")) return (byte)(b - '0");
        if ((b >= 'a") && (b <= 'f")) return (byte)(b - 'a" + 10);
        if ((b >= 'A") && (b <= 'F")) return (byte)(b - 'A" + 10);
        return 0;
    
private static java.lang.Objectparse(com.sun.grizzly.cometd.util.JSONParser$Source source)

        int comment_state=0;
        
        while(source.hasNext()) {
            char c=source.peek();
            
            // handle // or /* comment
            if(comment_state==1) {
                switch(c) {
                    case '/" :
                        comment_state=-1;
                        break;
                    case '*" :
                        comment_state=2;
                }
            }
            // handle /* */ comment
            else if (comment_state>1) {
                switch(c) {
                    case '*" :
                        comment_state=3;
                        break;
                    case '/" :
                        if (comment_state==3)
                            comment_state=0;
                        else
                            comment_state=2;
                        break;
                    default:
                        comment_state=2;
                }
            }
            // handle // comment
            else if (comment_state<0) {
                switch(c) {
                    case '\r" :
                    case '\n" :
                        comment_state=0;
                        break;
                    default:
                        break;
                }
            }
            // handle unknown
            else {
                switch(c) {
                    case '{" :
                        return parseObject(source);
                    case '[" :
                        return parseArray(source);
                    case '"" :
                        return parseString(source);
                    case '-" :
                        return parseNumber(source);
                        
                    case 'n" :
                        complete("null",source);
                        return null;
                    case 't" :
                        complete("true",source);
                        return Boolean.TRUE;
                    case 'f" :
                        complete("false",source);
                        return Boolean.FALSE;
                        
                    case '/" :
                        comment_state=1;
                        break;
                        
                    default :
                        if (Character.isDigit(c))
                            return parseNumber(source);
                        else if (Character.isWhitespace(c))
                            break;
                        
                        throw new IllegalStateException("unknown char "+c);
                }
            }
            source.next();
        }
        
        return null;
    
public static java.lang.Objectparse(java.lang.String s)

param
s String containing JSON object or array.
return
A Map, Object array or primitive array parsed from the JSON.

        return parse(new Source(s));
    
private static java.lang.ObjectparseArray(com.sun.grizzly.cometd.util.JSONParser$Source source)

        if (source.next()!='[")
            throw new IllegalStateException();
        
        ArrayList list=new ArrayList();
        boolean coma=true;
        
        while(source.hasNext()) {
            char c=source.peek();
            switch(c) {
                case ']":
                    source.next();
                    return list.toArray(new Object[list.size()]);
                    
                case ',":
                    if (coma)
                        throw new IllegalStateException();
                    coma=true;
                    source.next();
                    
                default:
                    if (Character.isWhitespace(c))
                        source.next();
                    else {
                        coma=false;
                        list.add(parse(source));
                    }
            }
            
        }
        
        throw new IllegalStateException("unexpected end of array");
    
private static java.lang.NumberparseNumber(com.sun.grizzly.cometd.util.JSONParser$Source source)

        int start=source.index();
        int end=-1;
        boolean is_double=false;
        while(source.hasNext()&&end<0) {
            char c=source.peek();
            switch(c) {
                case '0":
                case '1":
                case '2":
                case '3":
                case '4":
                case '5":
                case '6":
                case '7":
                case '8":
                case '9":
                case '-":
                    source.next();
                    break;
                    
                case '.":
                case 'e":
                case 'E":
                    is_double=true;
                    source.next();
                    break;
                    
                default:
                    end=source.index();
            }
        }
        String s = end>=0?source.from(start,end):source.from(start);
        if (is_double)
            return new Double(s);
        else
            return new Long(s);
    
private static java.util.MapparseObject(com.sun.grizzly.cometd.util.JSONParser$Source source)

        if (source.next()!='{")
            throw new IllegalStateException();
        Map map = new HashMap();
        
        char next = seekTo("\"}",source);
        
        while(source.hasNext()) {
            if (next=='}") {
                source.next();
                break;
            }
            
            String name=parseString(source);
            seekTo(':",source);
            source.next();
            
            Object value=parse(source);
            map.put(name,value);
            
            seekTo(",}",source);
            next=source.next();
            if (next=='}")
                break;
            else
                next = seekTo("\"}",source);
        }
        
        return map;
    
private static java.lang.StringparseString(com.sun.grizzly.cometd.util.JSONParser$Source source)

        if (source.next()!='"")
            throw new IllegalStateException();
        
        boolean escape=false;
        StringBuffer b = new StringBuffer();
        while(source.hasNext()) {
            char c=source.next();
            
            if (escape) {
                escape=false;
                switch (c) {
                    case 'n":
                        b.append('\n");
                        break;
                    case 'r":
                        b.append('\r");
                        break;
                    case 't":
                        b.append('\t");
                        break;
                    case 'f":
                        b.append('\f");
                        break;
                    case 'b":
                        b.append('\b");
                        break;
                    case 'u":
                        b.append((char)(
                                (convertHexDigit((byte)source.next())<<24)+
                                (convertHexDigit((byte)source.next())<<16)+
                                (convertHexDigit((byte)source.next())<<8)+
                                (convertHexDigit((byte)source.next()))
                                )
                                );
                        break;
                    default:
                        b.append(c);
                }
            } else if (c=='\\") {
                escape=true;
                continue;
            } else if (c=='\"")
                break;
            else
                b.append(c);
        }
        
        return b.toString();
    
public static java.lang.Stringquote(java.lang.String s)
Quote a string. The string is quoted only if quoting is required due to embeded delimiters, quote characters or the empty string.

param
s The string to quote.
return
quoted string

        if (s==null)
            return null;
        if (s.length()==0)
            return "\"\"";
        
        StringBuffer b=new StringBuffer(s.length()+8);
        quote(b,s);
        return b.toString();
   
    
public static voidquote(java.lang.StringBuffer buf, java.lang.String s)
Quote a string into a StringBuffer. The characters ", \, \n, \r, \t, \f and \b are escaped

param
buf The StringBuffer
param
s The String to quote.

        synchronized(buf)
        {
            buf.append('"");
            for (int i=0;i<s.length();i++)
            {
                char c = s.charAt(i);
                switch(c)
                {
                    case '"":
                        buf.append("\\\"");
                        continue;
                    case '\\":
                        buf.append("\\\\");
                        continue;
                    case '\n":
                        buf.append("\\n");
                        continue;
                    case '\r":
                        buf.append("\\r");
                        continue;
                    case '\t":
                        buf.append("\\t");
                        continue;
                    case '\f":
                        buf.append("\\f");
                        continue;
                    case '\b":
                        buf.append("\\b");
                        continue;
                        
                    default:
                        buf.append(c);
                        continue;
                }
            }
            buf.append('"");
        }
    
private static voidseekTo(char seek, com.sun.grizzly.cometd.util.JSONParser$Source source)

        while(source.hasNext()) {
            char c=source.peek();
            if (c==seek)
                return;
            
            if (!Character.isWhitespace(c))
                throw new IllegalStateException("Unexpected '"+c+" while seeking '"+seek+"'");
            source.next();
        }
        
        throw new IllegalStateException("Expected '"+seek+"'");
    
private static charseekTo(java.lang.String seek, com.sun.grizzly.cometd.util.JSONParser$Source source)

        while(source.hasNext()) {
            char c=source.peek();
            if(seek.indexOf(c)>=0) {
                return c;
            }
            
            if (!Character.isWhitespace(c))
                throw new IllegalStateException("Unexpected '"+c+"' while seeking one of '"+seek+"'");
            source.next();
        }
        
        throw new IllegalStateException("Expected one of '"+seek+"'");
    
public static java.lang.StringtoString(java.lang.Object object)

        StringBuffer buffer = new StringBuffer();
        append(buffer,object);
        return buffer.toString();
    
public static java.lang.StringtoString(java.util.Map object)

        StringBuffer buffer = new StringBuffer();
        appendMap(buffer,object);
        return buffer.toString();
    
public static java.lang.StringtoString(java.lang.Object[] array)

        StringBuffer buffer = new StringBuffer();
        appendArray(buffer,array);
        return buffer.toString();