View Javadoc

1   /*
2    * Copyright 2002-2009 the original author or authors.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package net.sf.json.groovy;
18  
19  import groovy.lang.GroovyObjectSupport;
20  
21  import java.io.BufferedReader;
22  import java.io.File;
23  import java.io.FileReader;
24  import java.io.IOException;
25  import java.io.InputStream;
26  import java.io.InputStreamReader;
27  import java.io.Reader;
28  import java.net.URL;
29  
30  import net.sf.json.JSON;
31  import net.sf.json.JSONSerializer;
32  import net.sf.json.JsonConfig;
33  
34  /**
35   * A Helper class modeled after XmlSlurper
36   * 
37   * @author Andres Almiray <aalmiray@users.sourceforge.net>
38   */
39  public class JsonSlurper extends GroovyObjectSupport {
40  
41     private JsonConfig jsonConfig;
42  
43     public JsonSlurper() {
44        this( new JsonConfig() );
45     }
46  
47     public JsonSlurper( JsonConfig jsonConfig ) {
48        this.jsonConfig = jsonConfig != null ? jsonConfig : new JsonConfig();
49     }
50  
51     public JSON parse( File file ) throws IOException {
52        return parse( new FileReader( file ) );
53     }
54  
55     public JSON parse( URL url ) throws IOException {
56        return parse( url.openConnection().getInputStream() );
57     }
58  
59     public JSON parse( InputStream input ) throws IOException {
60        return parse( new InputStreamReader( input ) );
61     }
62  
63     public JSON parse( String uri ) throws IOException {
64        return parse( new URL( uri ) );
65     }
66  
67     public JSON parse( Reader reader ) throws IOException {
68        // unfortunately JSONSerializer can't process the text as a stream
69        // so we must read the full content first and then parse it
70        StringBuffer buffer = new StringBuffer();
71        BufferedReader in = new BufferedReader( reader );
72        String line = null;
73        while( (line = in.readLine()) != null ) {
74           buffer.append( line ).append( "\n" );
75        }
76        return parseText( buffer.toString() );
77     }
78  
79     public JSON parseText( String text ) {
80        return JSONSerializer.toJSON( text, jsonConfig );
81     }
82  }