Open Source Repository

Home /json/json-lib-2.4-jdk13 | Repository Home



net/sf/json/groovy/JsonSlurper.java
/*
 * Copyright 2002-2009 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package net.sf.json.groovy;

import groovy.lang.GroovyObjectSupport;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;

import net.sf.json.JSON;
import net.sf.json.JSONSerializer;
import net.sf.json.JsonConfig;

/**
 * A Helper class modeled after XmlSlurper
 
 @author Andres Almiray <[email protected]>
 */
public class JsonSlurper extends GroovyObjectSupport {

   private JsonConfig jsonConfig;

   public JsonSlurper() {
      thisnew JsonConfig() );
   }

   public JsonSlurperJsonConfig jsonConfig ) {
      this.jsonConfig = jsonConfig != null ? jsonConfig : new JsonConfig();
   }

   public JSON parseFile file throws IOException {
      return parsenew FileReaderfile ) );
   }

   public JSON parseURL url throws IOException {
      return parseurl.openConnection().getInputStream() );
   }

   public JSON parseInputStream input throws IOException {
      return parsenew InputStreamReaderinput ) );
   }

   public JSON parseString uri throws IOException {
      return parsenew URLuri ) );
   }

   public JSON parseReader reader throws IOException {
      // unfortunately JSONSerializer can't process the text as a stream
      // so we must read the full content first and then parse it
      StringBuffer buffer = new StringBuffer();
      BufferedReader in = new BufferedReaderreader );
      String line = null;
      while( (line = in.readLine()) != null ) {
         buffer.appendline ).append"\n" );
      }
      return parseTextbuffer.toString() );
   }

   public JSON parseTextString text ) {
      return JSONSerializer.toJSONtext, jsonConfig );
   }
}