1 /* 2 * Copyright (C) 2015 The Android Open Source Project 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 com.android.statementservice.retriever; 18 19 import android.util.JsonReader; 20 import android.util.JsonToken; 21 22 import org.json.JSONArray; 23 import org.json.JSONException; 24 import org.json.JSONObject; 25 26 import java.io.IOException; 27 import java.util.ArrayList; 28 import java.util.List; 29 30 /** 31 * A helper class that creates a {@link JSONObject} from a {@link JsonReader}. 32 */ 33 public final class JsonParser { 34 JsonParser()35 private JsonParser() {} 36 37 /** 38 * Consumes and parses exactly one JSON object from the {@link JsonReader}. 39 * The object's fields can only be objects, strings or arrays of strings. 40 */ parse(JsonReader reader)41 public static JSONObject parse(JsonReader reader) throws IOException, JSONException { 42 JSONObject output = new JSONObject(); 43 String errorMsg = null; 44 45 reader.beginObject(); 46 while (reader.hasNext()) { 47 String fieldName = reader.nextName(); 48 49 if (output.has(fieldName)) { 50 errorMsg = "Duplicate field name."; 51 reader.skipValue(); 52 continue; 53 } 54 55 JsonToken token = reader.peek(); 56 if (token.equals(JsonToken.BEGIN_ARRAY)) { 57 output.put(fieldName, new JSONArray(parseArray(reader))); 58 } else if (token.equals(JsonToken.STRING)) { 59 output.put(fieldName, reader.nextString()); 60 } else if (token.equals(JsonToken.BEGIN_OBJECT)) { 61 try { 62 output.put(fieldName, parse(reader)); 63 } catch (JSONException e) { 64 errorMsg = e.getMessage(); 65 } 66 } else { 67 reader.skipValue(); 68 errorMsg = "Unsupported value type."; 69 } 70 } 71 reader.endObject(); 72 73 if (errorMsg != null) { 74 throw new JSONException(errorMsg); 75 } 76 77 return output; 78 } 79 80 /** 81 * Parses one string array from the {@link JsonReader}. 82 */ parseArray(JsonReader reader)83 public static List<String> parseArray(JsonReader reader) throws IOException { 84 ArrayList<String> output = new ArrayList<>(); 85 86 reader.beginArray(); 87 while (reader.hasNext()) { 88 output.add(reader.nextString()); 89 } 90 reader.endArray(); 91 92 return output; 93 } 94 } 95