BrightSide Workbench Full Report + Source Code
JsonReader.java
Go to the documentation of this file.
1 /*
2  * TurrĂ³ i Cutiller Foundation. License notice.
3  * Copyright (C) 2016 Lluis TurrĂ³ Cutiller <http://www.turro.org/>
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU Affero General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU Affero General Public License for more details.
14  *
15  * You should have received a copy of the GNU Affero General Public License
16  * along with this program. If not, see <http://www.gnu.org/licenses/>.
17  */
18 
19 package org.turro.elephant.impl.util;
20 
21 import com.jayway.jsonpath.DocumentContext;
22 import com.jayway.jsonpath.JsonPath;
23 import java.io.File;
24 import java.io.IOException;
25 import java.util.List;
26 import java.util.Map;
27 import org.turro.reflection.ReflectionUtil;
28 
33 public class JsonReader {
34 
35  private final File file;
36  private final String json;
37 
38  public JsonReader(File file) {
39  this.file = file;
40  this.json = null;
41  }
42 
43  public JsonReader(String json) {
44  this.json = json;
45  this.file = null;
46  }
47 
48  public List list(String path) throws IOException {
49  return load().read(path, java.util.List.class);
50  }
51 
52  public Map map(String path) throws IOException {
53  return load().read(path, java.util.Map.class);
54  }
55 
56  public String read(String path) throws IOException {
57  return load().read(path);
58  }
59 
60  public Object read(String path, String javaClass) throws IOException {
61  return load().read(path, ReflectionUtil.classCheck(javaClass));
62  }
63 
64  public <T> T read(String path, Class<T> javaClass) throws IOException {
65  return load().read(path, javaClass);
66  }
67 
68  public JsonReader put(String path, String key, Object value) throws IOException {
69  load().put(path, key, value);
70  return this;
71  }
72 
73  public JsonReader add(String path, Object value) throws IOException {
74  load().add(path, value);
75  return this;
76  }
77 
78  /* Parser */
79 
80  private DocumentContext _parser;
81 
82  private DocumentContext load() throws IOException {
83  if(_parser == null) {
84  if(file != null) {
85  _parser = JsonPath.parse(file);
86  } else {
87  _parser = JsonPath.parse(json);
88  }
89  }
90  return _parser;
91  }
92 
93 }
JsonReader put(String path, String key, Object value)
Definition: JsonReader.java:68
Object read(String path, String javaClass)
Definition: JsonReader.java:60
JsonReader add(String path, Object value)
Definition: JsonReader.java:73