Advertisement
iPeer

Untitled

Nov 17th, 2012
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.71 KB | None | 0 0
  1. import java.io.File;
  2. import java.io.FileInputStream;
  3. import java.io.FileNotFoundException;
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6. import java.net.MalformedURLException;
  7. import java.net.URL;
  8. import java.util.HashMap;
  9. import java.util.Map;
  10. import java.util.Scanner;
  11.  
  12. public class JSONReader {
  13.  
  14.     private Map<String, String> data = new HashMap<String, String>();
  15.  
  16.     public JSONReader(String file) throws EmptyJSONFileException, MalformedURLException, IOException {
  17.         this(new URL(file));
  18.     }
  19.  
  20.     public JSONReader(URL file) throws IOException, EmptyJSONFileException {
  21.         InputStream in;
  22.         in = file.openStream();
  23.         Scanner s = new Scanner(in, "UTF-8");
  24.         while (s.hasNextLine())
  25.             parse(s.nextLine());
  26.         s.close();
  27.     }
  28.  
  29.     public JSONReader(File file) throws FileNotFoundException, EmptyJSONFileException {
  30.         InputStream in;
  31.         in = new FileInputStream(file);
  32.         Scanner s = new Scanner(in, "UTF-8");
  33.         while (s.hasNextLine())
  34.             parse(s.nextLine());
  35.         s.close();
  36.     }
  37.  
  38.     private void parse(String s) throws EmptyJSONFileException {
  39.         if (s.equals("[]"))
  40.             throw new EmptyJSONFileException();
  41.         String[] data1 = s.split(",\"");
  42.         for (String a : data1) {
  43.             String[] ddata = a.replaceAll("\\}\\]|\\{\\[|\\[\\{\"|\\}", "").split("\":");
  44.             data.put(ddata[0], trim(ddata[1]));
  45.         }
  46.     }
  47.  
  48.     public String get(String key) {
  49.         try {
  50.             return data.get(key);
  51.         }
  52.         catch (NullPointerException e) {
  53.             return "";
  54.         }
  55.     }
  56.  
  57.     private String trim(String s) {
  58.         if (s.startsWith("\"") && s.endsWith("\""))
  59.             return s.substring(1, s.length() - 1);
  60.         else if (s.startsWith("\""))
  61.             return s.substring(1);
  62.         else if (s.endsWith("\""))
  63.             return s.substring(0, s.length() - 1);
  64.         return s;
  65.     }
  66.  
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement