Java 类com.google.gson.stream.JsonReader 实例源码

项目:boohee_v5.6    文件:Gson.java   
public <T> T fromJson(JsonReader reader, Type typeOfT) throws JsonIOException,
        JsonSyntaxException {
    boolean isEmpty = true;
    boolean oldLenient = reader.isLenient();
    reader.setLenient(true);
    try {
        reader.peek();
        isEmpty = false;
        T object = getAdapter(TypeToken.get(typeOfT)).read(reader);
        reader.setLenient(oldLenient);
        return object;
    } catch (Throwable e) {
        if (isEmpty) {
            reader.setLenient(oldLenient);
            return null;
        }
        throw new JsonSyntaxException(e);
    } catch (Throwable e2) {
        throw new JsonSyntaxException(e2);
    } catch (Throwable e22) {
        throw new JsonSyntaxException(e22);
    } catch (Throwable th) {
        reader.setLenient(oldLenient);
    }
}
项目:boohee_v5.6    文件:Gson.java   
private TypeAdapter<Number> longAdapter(LongSerializationPolicy longSerializationPolicy) {
    if (longSerializationPolicy == LongSerializationPolicy.DEFAULT) {
        return TypeAdapters.LONG;
    }
    return new TypeAdapter<Number>() {
        public Number read(JsonReader in) throws IOException {
            if (in.peek() != JsonToken.NULL) {
                return Long.valueOf(in.nextLong());
            }
            in.nextNull();
            return null;
        }

        public void write(JsonWriter out, Number value) throws IOException {
            if (value == null) {
                out.nullValue();
            } else {
                out.value(value.toString());
            }
        }
    };
}
项目:letv    文件:TypeAdapters.java   
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
    if (typeToken.getRawType() != Timestamp.class) {
        return null;
    }
    final TypeAdapter<Date> dateTypeAdapter = gson.getAdapter(Date.class);
    return new TypeAdapter<Timestamp>() {
        public Timestamp read(JsonReader in) throws IOException {
            Date date = (Date) dateTypeAdapter.read(in);
            return date != null ? new Timestamp(date.getTime()) : null;
        }

        public void write(JsonWriter out, Timestamp value) throws IOException {
            dateTypeAdapter.write(out, value);
        }
    };
}
项目:boohee_v5.6    文件:ReflectiveTypeAdapterFactory.java   
public T read(JsonReader in) throws IOException {
    if (in.peek() == JsonToken.NULL) {
        in.nextNull();
        return null;
    }
    T instance = this.constructor.construct();
    try {
        in.beginObject();
        while (in.hasNext()) {
            BoundField field = (BoundField) this.boundFields.get(in.nextName());
            if (field == null || !field.deserialized) {
                in.skipValue();
            } else {
                field.read(in, instance);
            }
        }
        in.endObject();
        return instance;
    } catch (Throwable e) {
        throw new JsonSyntaxException(e);
    } catch (IllegalAccessException e2) {
        throw new AssertionError(e2);
    }
}
项目:Enjin-Coin-Java-SDK    文件:JsonUtilsTest.java   
@Test
public void testConvertJsonFromFileReaderToObject_Success() throws Exception {
    FileReader mockFileReader = Mockito.mock(FileReader.class);
    Class<?> responseClass = GetEventResponseVO.class;

    Gson mockGson = PowerMockito.mock(Gson.class);
    JsonReader mockJsonReader = Mockito.mock(JsonReader.class);

    PowerMockito.whenNew(JsonReader.class).withArguments(Mockito.isA(FileReader.class)).thenReturn(mockJsonReader);
    Mockito.when(mockGson.fromJson(Mockito.isA(JsonReader.class), Mockito.isA(Class.class))).thenReturn(ImmutableGetEventResponseVO.builder().build());
    Object responseObject = JsonUtils.convertJsonFromFileReaderToObject(mockGson, mockFileReader, responseClass);
    assertThat(responseObject).isNotNull();

    PowerMockito.verifyNew(JsonReader.class, Mockito.times(1)).withArguments(Mockito.isA(FileReader.class));
    Mockito.verify(mockGson, Mockito.times(1)).fromJson(Mockito.isA(JsonReader.class), Mockito.isA(Class.class));
}
项目:justintrain-client-android    文件:PostProcessingEnabler.java   
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
    final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);

    return new TypeAdapter<T>() {
        public void write(JsonWriter out, T value) throws IOException {
            delegate.write(out, value);
        }

        public T read(JsonReader in) throws IOException {
            T obj = delegate.read(in);
            if (obj instanceof PostProcessable) {
                ((PostProcessable) obj).postProcess();
            }
            return obj;
        }
    };
}
项目:odoo-work    文件:Gson.java   
private TypeAdapter<Number> floatAdapter(boolean serializeSpecialFloatingPointValues) {
  if (serializeSpecialFloatingPointValues) {
    return TypeAdapters.FLOAT;
  }
  return new TypeAdapter<Number>() {
    @Override public Float read(JsonReader in) throws IOException {
      if (in.peek() == JsonToken.NULL) {
        in.nextNull();
        return null;
      }
      return (float) in.nextDouble();
    }
    @Override public void write(JsonWriter out, Number value) throws IOException {
      if (value == null) {
        out.nullValue();
        return;
      }
      float floatValue = value.floatValue();
      checkValidFloatingPoint(floatValue);
      out.value(value);
    }
  };
}
项目:boohee_v5.6    文件:TypeAdapter.java   
public final TypeAdapter<T> nullSafe() {
    return new TypeAdapter<T>() {
        public void write(JsonWriter out, T value) throws IOException {
            if (value == null) {
                out.nullValue();
            } else {
                TypeAdapter.this.write(out, value);
            }
        }

        public T read(JsonReader reader) throws IOException {
            if (reader.peek() != JsonToken.NULL) {
                return TypeAdapter.this.read(reader);
            }
            reader.nextNull();
            return null;
        }
    };
}
项目:pcloud-sdk-java    文件:RealApiClient.java   
private <T> T deserializeResponseBody(Response response, Class<? extends T> bodyType) throws IOException {
    try {
        if (!response.isSuccessful()) {
            throw new APIHttpException(response.code(), response.message());
        }

        JsonReader reader = new JsonReader(new BufferedReader(new InputStreamReader(response.body().byteStream())));
        try {
            return gson.fromJson(reader, bodyType);
        } catch (JsonSyntaxException e) {
            throw new IOException("Malformed JSON response.", e);
        } finally {
            closeQuietly(reader);
        }
    } finally {
        closeQuietly(response);
    }
}
项目:boohee_v5.6    文件:JsonParser.java   
public JsonElement parse(Reader json) throws JsonIOException, JsonSyntaxException {
    try {
        JsonReader jsonReader = new JsonReader(json);
        JsonElement element = parse(jsonReader);
        if (element.isJsonNull() || jsonReader.peek() == JsonToken.END_DOCUMENT) {
            return element;
        }
        throw new JsonSyntaxException("Did not consume the entire document.");
    } catch (Throwable e) {
        throw new JsonSyntaxException(e);
    } catch (Throwable e2) {
        throw new JsonIOException(e2);
    } catch (Throwable e22) {
        throw new JsonSyntaxException(e22);
    }
}
项目:letv    文件:TypeAdapter.java   
public final TypeAdapter<T> nullSafe() {
    return new TypeAdapter<T>() {
        public void write(JsonWriter out, T value) throws IOException {
            if (value == null) {
                out.nullValue();
            } else {
                TypeAdapter.this.write(out, value);
            }
        }

        public T read(JsonReader reader) throws IOException {
            if (reader.peek() != JsonToken.NULL) {
                return TypeAdapter.this.read(reader);
            }
            reader.nextNull();
            return null;
        }
    };
}
项目:lams    文件:Gson.java   
private TypeAdapter<Number> longAdapter(LongSerializationPolicy longSerializationPolicy) {
  if (longSerializationPolicy == LongSerializationPolicy.DEFAULT) {
    return TypeAdapters.LONG;
  }
  return new TypeAdapter<Number>() {
    @Override public Number read(JsonReader in) throws IOException {
      if (in.peek() == JsonToken.NULL) {
        in.nextNull();
        return null;
      }
      return in.nextLong();
    }
    @Override public void write(JsonWriter out, Number value) throws IOException {
      if (value == null) {
        out.nullValue();
        return;
      }
      out.value(value.toString());
    }
  };
}
项目:PI-Web-API-Client-Java-Android    文件:JSON.java   
/**
 * Deserialize the given JSON string to Java object.
 *
 * @param <T> Type
 * @param body The JSON string
 * @param returnType The type to deserialize into
 * @return The deserialized Java object
 */
@SuppressWarnings("unchecked")
public <T> T deserialize(String body, Type returnType) {
    try {
        if (apiClient.isLenientOnJson()) {
            JsonReader jsonReader = new JsonReader(new StringReader(body));
            // see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean)
            jsonReader.setLenient(true);
            return gson.fromJson(jsonReader, returnType);
        } else {
            return gson.fromJson(body, returnType);
        }
    } catch (JsonParseException e) {
        // Fallback processing when failed to parse JSON form response body:
        //   return the response body string directly for the String return type;
        //   parse response body into date or datetime for the Date return type.
        if (returnType.equals(String.class))
            return (T) body;
        else if (returnType.equals(Date.class))
            return (T) apiClient.parseDateOrDatetime(body);
        else throw(e);
    }
}
项目:ULCRS    文件:SessionControllerTest.java   
@Before
public void init() throws Exception {
    MockitoAnnotations.initMocks(this);

    sessionControllerTest = new SessionController();

    directoryTest = new File(TEST_WORKSPACE_PATH);
    fileReaderTest = new FileReader(TEST_WORKSPACE_PATH + "2.json");

    Mockito.when(requestMock.params(Mockito.eq(":name"))).thenReturn("2");

    InputStream is = SessionController.class.getClassLoader().getResourceAsStream("mockSessionSchedule.json");
    JsonReader reader = new JsonReader(new InputStreamReader(is));
    Schedule schedule = gson.fromJson(reader, new TypeToken<Schedule>() {
    }.getType());
    String scheduleStrTest = gson.toJson(schedule);
    Mockito.when(requestMock.body()).thenReturn(scheduleStrTest);

    PowerMockito.whenNew(File.class).withParameterTypes(String.class)
            .withArguments(Mockito.eq(WORKSPACE_PATH)).thenReturn(directoryTest);
    PowerMockito.whenNew(FileReader.class).withParameterTypes(String.class)
            .withArguments(Mockito.eq(WORKSPACE_PATH + "2.json")).thenReturn(fileReaderTest);
}
项目:data-mediator    文件:TypeHandler.java   
@Override
public void read(JsonReader in, GsonProperty property, Object t) throws IOException {
    final Class<?> simpleType = property.getType();

    List list = new ArrayList();
    in.beginArray();
    if (simpleType.isPrimitive() || isBoxedClass(simpleType)) {
        while (in.hasNext()){
            list.add(SupportUtils.readPrimitiveOrItsBox(in, property));
        }
    }else{
        TypeAdapter adapter = getTypeAdapter(simpleType);
        while (in.hasNext()){
            list.add(adapter.read(in));
        }
    }
    //copy to array
    Object array = Array.newInstance(simpleType, list.size());
    for(int i = 0, size = list.size() ; i < size ; i ++){
        Array.set(array, i, list.get(i));
    }
    setValue(property, t, array);
    in.endArray();
}
项目:boohee_v5.6    文件:TypeAdapters.java   
public Boolean read(JsonReader in) throws IOException {
    if (in.peek() == JsonToken.NULL) {
        in.nextNull();
        return null;
    } else if (in.peek() == JsonToken.STRING) {
        return Boolean.valueOf(Boolean.parseBoolean(in.nextString()));
    } else {
        return Boolean.valueOf(in.nextBoolean());
    }
}
项目:synthea_java    文件:ConceptsTest.java   
@Test
public void testInventoryState() throws FileNotFoundException {
  Path modulesFolder = Paths.get("src/test/resources/generic");
  Path modulePath = modulesFolder.resolve("condition_onset.json");

  JsonReader reader = new JsonReader(new FileReader(modulePath.toString()));
  JsonObject module = new JsonParser().parse(reader).getAsJsonObject();
  JsonObject state = module.getAsJsonObject("states").getAsJsonObject("Appendicitis");

  Concepts.inventoryState(concepts, state);

  assertEquals(1, concepts.cellSet().size());
  assertEquals("Rupture of appendix", concepts.get("SNOMED-CT", "47693006"));
}
项目:lams    文件:TypeAdapters.java   
@Override
public Locale read(JsonReader in) throws IOException {
  if (in.peek() == JsonToken.NULL) {
    in.nextNull();
    return null;
  }
  String locale = in.nextString();
  StringTokenizer tokenizer = new StringTokenizer(locale, "_");
  String language = null;
  String country = null;
  String variant = null;
  if (tokenizer.hasMoreElements()) {
    language = tokenizer.nextToken();
  }
  if (tokenizer.hasMoreElements()) {
    country = tokenizer.nextToken();
  }
  if (tokenizer.hasMoreElements()) {
    variant = tokenizer.nextToken();
  }
  if (country == null && variant == null) {
    return new Locale(language);
  } else if (variant == null) {
    return new Locale(language, country);
  } else {
    return new Locale(language, country, variant);
  }
}
项目:CustomWorldGen    文件:JsonUtils.java   
public static <T> T gsonDeserialize(Gson gsonIn, Reader readerIn, Class<T> adapter, boolean lenient)
{
    try
    {
        JsonReader jsonreader = new JsonReader(readerIn);
        jsonreader.setLenient(lenient);
        return gsonIn.getAdapter(adapter).read(jsonreader);
    }
    catch (IOException ioexception)
    {
        throw new JsonParseException(ioexception);
    }
}
项目:ZentrelaCore    文件:LocationAdapter.java   
@Override
public Location read(JsonReader in) throws IOException {
    World w = null;
    String worldString = "";
    double x = 0, y = 0, z = 0;
    float yaw = 0, pitch = 0;
    in.beginObject();
    while (in.hasNext()) {
        switch (in.nextName()) {
            case "x":
                x = in.nextDouble();
                break;
            case "y":
                y = in.nextDouble();
                break;
            case "z":
                z = in.nextDouble();
                break;
            case "yaw":
                yaw = (float) in.nextDouble();
                break;
            case "pitch":
                pitch = (float) in.nextDouble();
                break;
            case "worldString":
                worldString = in.nextString();
                break;
        }
    }
    in.endObject();
    w = SakiCore.plugin.getServer().getWorld(worldString);
    if (w == null)
        throw new IOException("Invalid world in JSON: " + worldString + ".");
    return new Location(w, x, y, z, yaw, pitch);
}
项目:ForgeHax    文件:BlockEntry.java   
@Override
public void deserialize(final JsonReader reader) throws IOException {
    reader.beginObject();
    while(reader.hasNext()) {
        String name = reader.nextName();
        IBlockProperty property = PropertyFactory.newInstance(name);
        if(property != null) {
            property.deserialize(reader);
            registerProperty(property);
        } else {
            LOGGER.warn(String.format("\"%s\" is not a valid property name", name));
        }
    }
    reader.endObject();
}
项目:boohee_v5.6    文件:TypeAdapters.java   
public JsonElement read(JsonReader in) throws IOException {
    switch (in.peek()) {
        case NUMBER:
            return new JsonPrimitive(new LazilyParsedNumber(in.nextString()));
        case BOOLEAN:
            return new JsonPrimitive(Boolean.valueOf(in.nextBoolean()));
        case STRING:
            return new JsonPrimitive(in.nextString());
        case NULL:
            in.nextNull();
            return JsonNull.INSTANCE;
        case BEGIN_ARRAY:
            JsonElement array = new JsonArray();
            in.beginArray();
            while (in.hasNext()) {
                array.add(read(in));
            }
            in.endArray();
            return array;
        case BEGIN_OBJECT:
            JsonElement object = new JsonObject();
            in.beginObject();
            while (in.hasNext()) {
                object.add(in.nextName(), read(in));
            }
            in.endObject();
            return object;
        default:
            throw new IllegalArgumentException();
    }
}
项目:GitHub    文件:JsonConvert.java   
private T parseType(Response response, Type type) throws Exception {
    if (type == null) return null;
    ResponseBody body = response.body();
    if (body == null) return null;
    JsonReader jsonReader = new JsonReader(body.charStream());

    // 泛型格式如下: new JsonCallback<任意JavaBean>(this)
    T t = Convert.fromJson(jsonReader, type);
    response.close();
    return t;
}
项目:boohee_v5.6    文件:CollectionTypeAdapterFactory.java   
public Collection<E> read(JsonReader in) throws IOException {
    if (in.peek() == JsonToken.NULL) {
        in.nextNull();
        return null;
    }
    Collection<E> collection = (Collection) this.constructor.construct();
    in.beginArray();
    while (in.hasNext()) {
        collection.add(this.elementTypeAdapter.read(in));
    }
    in.endArray();
    return collection;
}
项目:ForgeHax    文件:BoundProperty.java   
@Override
public void deserialize(JsonReader reader) throws IOException {
    reader.beginArray();
    while(reader.hasNext()) {
        reader.beginArray();
        add(reader.nextInt(), reader.nextInt());
        reader.endArray();
    }
    reader.endArray();
}
项目:lams    文件:TypeAdapters.java   
@Override
public InetAddress read(JsonReader in) throws IOException {
  if (in.peek() == JsonToken.NULL) {
    in.nextNull();
    return null;
  }
  // regrettably, this should have included both the host name and the host address
  return InetAddress.getByName(in.nextString());
}
项目:XXXX    文件:GsonCodecTest.java   
@Override
public Zone read(JsonReader in) throws IOException {
  in.beginObject();
  Zone zone = new Zone();
  while (in.hasNext()) {
    zone.put(in.nextName(), in.nextString().toUpperCase());
  }
  in.endObject();
  return zone;
}
项目:lams    文件:TypeAdapters.java   
@Override public Boolean read(JsonReader in) throws IOException {
  if (in.peek() == JsonToken.NULL) {
    in.nextNull();
    return null;
  }
  return Boolean.valueOf(in.nextString());
}
项目:ULCRS    文件:SessionController.java   
private Session getSession(Request request, Response response) throws IOException {
    response.type(CONTENT_TYPE_JSON);
    String name = addJsonExtension(request.params(":name"));

    try {
        FileReader fileReader = new FileReader(WORKSPACE_PATH + name);
        JsonReader reader = new JsonReader(fileReader);
        return gson.fromJson(reader, new TypeToken<Session>() {
        }.getType());
    } catch (FileNotFoundException e) {
        log.warn("File " + WORKSPACE_PATH + name + " not found.");
        return null;
    }
}
项目:ZhiHuIndex-master    文件:GsonTool.java   
public static List<User> getuList(String jsonString) {
    List<User> uList = new ArrayList<User>();
    try {
        Gson gson = new Gson();
        Type type = new TypeToken<List<User>>(){}.getType();
        JsonReader jsonReader = new JsonReader(new StringReader(jsonString));
        jsonReader.setLenient(true);
        uList = gson.fromJson(jsonReader, type);
    } catch (JsonSyntaxException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return uList;
}
项目:data-mediator    文件:Car3TypeAdapter.java   
@Override
public Car3 read(JsonReader reader) throws IOException {

    Car3 car = new Car3();
    reader.beginObject();
    while (reader.hasNext()) {
        String name = reader.nextName();
        if (name.equals("mark")) {
            car.setMark(reader.nextString());
        } else if (name.equals("model")) {
            car.setModel(reader.nextInt());
        } else if (name.equals("type")) {
            car.setType(reader.nextString());
        } else if (name.equals("maker")) {
            car.setType(reader.nextString());
        } else if (name.equals("cost")) {
            double cost = reader.nextDouble();
            double costExcludingVAT = cost / 1.21;
            car.setCost(costExcludingVAT);  //Remove VAT 21%
        } else if (name.equals("colors") && reader.peek() != JsonToken.NULL) {
            car.setColors(readStringArray(reader));
        } else {
            reader.skipValue();
        }
    }
    reader.endObject();
    return car;
}
项目:AURdroid    文件:AurRpcService.java   
@Override
public String read(JsonReader in) throws IOException {
    if (in.peek() == JsonToken.NULL) {
        in.nextNull();
        return "";
    }
    return in.nextString();
}
项目:letv    文件:Gson.java   
private static void assertFullConsumption(Object obj, JsonReader reader) {
    if (obj != null) {
        try {
            if (reader.peek() != JsonToken.END_DOCUMENT) {
                throw new JsonIOException("JSON document was not fully consumed.");
            }
        } catch (Throwable e) {
            throw new JsonSyntaxException(e);
        } catch (Throwable e2) {
            throw new JsonIOException(e2);
        }
    }
}
项目:letv    文件:BigDecimalTypeAdapter.java   
public BigDecimal read(JsonReader in) throws IOException {
    if (in.peek() == JsonToken.NULL) {
        in.nextNull();
        return null;
    }
    try {
        return new BigDecimal(in.nextString());
    } catch (Throwable e) {
        throw new JsonSyntaxException(e);
    }
}
项目:odoo-work    文件:CollectionTypeAdapterFactory.java   
public Collection<E> read(JsonReader in) throws IOException {
  if (in.peek() == JsonToken.NULL) {
    in.nextNull();
    return null;
  }

  Collection<E> collection = constructor.construct();
  in.beginArray();
  while (in.hasNext()) {
    E instance = elementTypeAdapter.read(in);
    collection.add(instance);
  }
  in.endArray();
  return collection;
}
项目:lams    文件:TypeAdapters.java   
@Override
public URI read(JsonReader in) throws IOException {
  if (in.peek() == JsonToken.NULL) {
    in.nextNull();
    return null;
  }
  try {
    String nextString = in.nextString();
    return "null".equals(nextString) ? null : new URI(nextString);
  } catch (URISyntaxException e) {
    throw new JsonIOException(e);
  }
}
项目:odoo-work    文件:TypeAdapters.java   
@Override public BigDecimal read(JsonReader in) throws IOException {
  if (in.peek() == JsonToken.NULL) {
    in.nextNull();
    return null;
  }
  try {
    return new BigDecimal(in.nextString());
  } catch (NumberFormatException e) {
    throw new JsonSyntaxException(e);
  }
}
项目:odoo-work    文件:Excluder.java   
public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type) {
  Class<?> rawType = type.getRawType();
  final boolean skipSerialize = excludeClass(rawType, true);
  final boolean skipDeserialize = excludeClass(rawType, false);

  if (!skipSerialize && !skipDeserialize) {
    return null;
  }

  return new TypeAdapter<T>() {
    /** The delegate is lazily created because it may not be needed, and creating it may fail. */
    private TypeAdapter<T> delegate;

    @Override public T read(JsonReader in) throws IOException {
      if (skipDeserialize) {
        in.skipValue();
        return null;
      }
      return delegate().read(in);
    }

    @Override public void write(JsonWriter out, T value) throws IOException {
      if (skipSerialize) {
        out.nullValue();
        return;
      }
      delegate().write(out, value);
    }

    private TypeAdapter<T> delegate() {
      TypeAdapter<T> d = delegate;
      return d != null
          ? d
          : (delegate = gson.getDelegateAdapter(Excluder.this, type));
    }
  };
}
项目:cyberduck    文件:JsonBookmarkCollection.java   
protected String readNext(final String name, final JsonReader reader) throws IOException {
    if(reader.peek() != JsonToken.NULL) {
        return reader.nextString();
    }
    else {
        reader.skipValue();
        log.warn(String.format("No value for key %s", name));
        return null;
    }
}
项目:lams    文件:TypeAdapters.java   
@Override
public Number read(JsonReader in) throws IOException {
  if (in.peek() == JsonToken.NULL) {
    in.nextNull();
    return null;
  }
  try {
    int intValue = in.nextInt();
    return (byte) intValue;
  } catch (NumberFormatException e) {
    throw new JsonSyntaxException(e);
  }
}