2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.controller.sal.rest.gson;
10 import com.google.gson.JsonArray;
11 import com.google.gson.JsonElement;
12 import com.google.gson.JsonIOException;
13 import com.google.gson.JsonNull;
14 import com.google.gson.JsonObject;
15 import com.google.gson.JsonParseException;
16 import com.google.gson.JsonPrimitive;
17 import com.google.gson.JsonSyntaxException;
18 import com.google.gson.internal.LazilyParsedNumber;
19 import com.google.gson.stream.JsonReader;
20 import com.google.gson.stream.MalformedJsonException;
21 import java.io.EOFException;
22 import java.io.IOException;
25 * This class parses JSON elements from a gson JsonReader. It disallows multiple elements of the same name unlike the
26 * default gson JsonParser."
28 public class JsonParser {
29 public JsonElement parse(JsonReader reader) throws JsonIOException, JsonSyntaxException {
30 // code copied from gson's JsonParser and Stream classes
32 boolean lenient = reader.isLenient();
33 reader.setLenient(true);
34 boolean isEmpty = true;
39 } catch (EOFException e) {
41 return JsonNull.INSTANCE;
43 // The stream ended prematurely so it is likely a syntax error.
44 throw new JsonSyntaxException(e);
45 } catch (MalformedJsonException e) {
46 throw new JsonSyntaxException(e);
47 } catch (IOException e) {
48 throw new JsonIOException(e);
49 } catch (NumberFormatException e) {
50 throw new JsonSyntaxException(e);
51 } catch (StackOverflowError | OutOfMemoryError e) {
52 throw new JsonParseException("Failed parsing JSON source: " + reader + " to Json", e);
54 reader.setLenient(lenient);
58 public JsonElement read(JsonReader in) throws IOException {
61 return new JsonPrimitive(in.nextString());
63 String number = in.nextString();
64 return new JsonPrimitive(new LazilyParsedNumber(number));
66 return new JsonPrimitive(in.nextBoolean());
69 return JsonNull.INSTANCE;
71 JsonArray array = new JsonArray();
73 while (in.hasNext()) {
79 JsonObject object = new JsonObject();
81 while (in.hasNext()) {
82 final String childName = in.nextName();
83 if (object.has(childName)) {
84 throw new JsonSyntaxException("Duplicate name " + childName + " in JSON input.");
86 object.add(childName, read(in));
95 throw new IllegalArgumentException();