Datasets:

ArXiv:
License:
File size: 2,026 Bytes
c574d3a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package httpcli.adapter.json;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class JSON {

  public static JSON of(String json) throws JSONException {
    if (json == null) 
      throw new JSONException("json == null");

    if (json.isEmpty()) 
      throw new JSONException("json is empty");

    int c = json.charAt(0);
    switch (c) {
      case '{':
        return new JSON(new JSONObject(json), null);

      case '[':
        return new JSON(null, new JSONArray(json));

      default:
        throw new JSONException("invalidate: " + json);
    }
  }
  
  private final JSONObject object;
  private final JSONArray array;
  private final boolean isObject;
  private final boolean isArray;

  JSON(JSONObject object, JSONArray array) {
    this.object = object;
    this.array = array;
    this.isObject = object != null;
    this.isArray = array != null;
  }

  public JSONObject getObject() {
    return object;
  }

  public JSONObject optObject(JSONObject defaultVal) {
    return isObject() ? getObject() : defaultVal;
  }
  
  public JSONObject optObject() {
    return isObject() ? getObject() : new JSONObject();
  }

  public JSONArray getArray() {
    return array;
  }

  public JSONArray optArray(JSONArray defaultVal) {
    return isArray() ? getArray() : defaultVal;
  }
  
  public JSONArray optArray() {
    return isArray() ? getArray() : new JSONArray();
  }

  public boolean isObject() {
    return isObject;
  }

  public boolean isArray() {
    return isArray;
  }

  public String toString(int indentFactor) {
    try {
        if (isArray()) 
            return array.toString(indentFactor);
        if (isObject()) 
            return object.toString(indentFactor);
        
        return null;
        
    } catch(Exception e) {
        return toString();
    }
  }

  @Override public String toString() {
    if (isArray()) 
        return array.toString();
    if (isObject()) 
        return object.toString();
    
    return null;
  }
}