当前位置: 首页>>代码示例>>Java>>正文


Java JsonParser类代码示例

本文整理汇总了Java中com.google.api.client.json.JsonParser的典型用法代码示例。如果您正苦于以下问题:Java JsonParser类的具体用法?Java JsonParser怎么用?Java JsonParser使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


JsonParser类属于com.google.api.client.json包,在下文中一共展示了JsonParser类的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: parseResponse

import com.google.api.client.json.JsonParser; //导入依赖的package包/类
/**
 * Parse the response from the HTTP call into an instance of the given class.
 *
 * @param response The parsed response object
 * @param c The class to instantiate and use to build the response object
 * @return The ApiResponse object
 * @throws IOException Any IO errors
 */
protected ApiResponse parseResponse(HttpResponse response, Class<?> c) throws IOException {
  ApiResponse res = null;
  InputStream in = response.getContent();

  if (in == null) {
    try {
      res = (ApiResponse)c.newInstance();
    } catch(ReflectiveOperationException e) {
      throw new RuntimeException("Cannot instantiate " + c, e);
    }
  } else {
    try {
      JsonParser jsonParser = GsonFactory.getDefaultInstance().createJsonParser(in);
      res = (ApiResponse)jsonParser.parse(c);
    } finally {
      in.close();
    }
  }

  res.setHttpRequest(response.getRequest());
  res.setHttpResponse(response);

  return res;
}
 
开发者ID:dnsimple,项目名称:dnsimple-java,代码行数:33,代码来源:HttpEndpointClient.java

示例2: getTableSchema

import com.google.api.client.json.JsonParser; //导入依赖的package包/类
/**
 * Gets the output table schema based on the given configuration.
 *
 * @param conf the configuration to reference the keys from.
 * @return the derived table schema, null if no table schema exists in the configuration.
 * @throws IOException if a table schema was set in the configuration but couldn't be parsed.
 */
public static TableSchema getTableSchema(Configuration conf) throws IOException {
  String outputSchema = conf.get(BigQueryConfiguration.OUTPUT_TABLE_SCHEMA_KEY);
  if (!Strings.isNullOrEmpty(outputSchema)) {
    try {
      List<TableFieldSchema> fields = new ArrayList<TableFieldSchema>();
      JsonParser parser = JacksonFactory.getDefaultInstance().createJsonParser(outputSchema);
      parser.parseArrayAndClose(fields, TableFieldSchema.class);

      return new TableSchema().setFields(fields);
    } catch (IOException e) {
      throw new IOException(
          "Unable to parse key '" + BigQueryConfiguration.OUTPUT_TABLE_SCHEMA_KEY + "'.", e);
    }
  }
  return null;
}
 
开发者ID:GoogleCloudPlatform,项目名称:bigdata-interop,代码行数:24,代码来源:BigQueryOutputConfiguration.java

示例3: performSearch

import com.google.api.client.json.JsonParser; //导入依赖的package包/类
private static List<Place> performSearch( String kind, String type, double lat, double lng )
    throws IOException
{
  HttpTransport httpTransport = new NetHttpTransport();
  HttpRequestFactory hrf = httpTransport.createRequestFactory();
  
  String paramsf = "%s?location=%f,%f&rankby=distance&keyword=%s&type=%s&sensor=true&key=%s";
  String params = String.format(paramsf, SearchData.BASE_URL, lat, lng, type, kind, AuthUtils.API_KEY);
  GenericUrl url = new GenericUrl(params);
  HttpRequest hreq = hrf.buildGetRequest(url);
  HttpResponse hres = hreq.execute();

  InputStream content = hres.getContent();
  JsonParser p = new JacksonFactory().createJsonParser(content);
  SearchData searchData = p.parse(SearchData.class, null);
  
  return searchData.buildPlaces();
}
 
开发者ID:coderoshi,项目名称:glass,代码行数:19,代码来源:PlaceUtils.java

示例4: populateDetails

import com.google.api.client.json.JsonParser; //导入依赖的package包/类
private static Place populateDetails( Place place )
      throws IOException
  {
    // grab more restaurant details
    HttpTransport httpTransport = new NetHttpTransport();
    HttpRequestFactory hrf = httpTransport.createRequestFactory();

    String paramsf = "%s?reference=%s&sensor=true&key=%s";
    String params = String.format(paramsf, DetailsData.BASE_URL, place.getReference(), AuthUtils.API_KEY);
    GenericUrl url = new GenericUrl(params);
    HttpRequest hreq = hrf.buildGetRequest(url);
    HttpResponse hres = hreq.execute();

//    ByteArrayOutputStream os = new ByteArrayOutputStream();
//    IOUtils.copy(hres.getContent(), os, false);
//    System.out.println( os.toString() );

    InputStream content2 = hres.getContent();
    JsonParser p = new JacksonFactory().createJsonParser(content2);
    DetailsData details = p.parse(DetailsData.class, null);
    details.populatePlace( place );

    return place;
  }
 
开发者ID:coderoshi,项目名称:glass,代码行数:25,代码来源:PlaceUtils.java

示例5: initializeParser

import com.google.api.client.json.JsonParser; //导入依赖的package包/类
/**
 * Initialize the parser to skip to wrapped keys (if any).
 *
 * @param parser JSON parser
 */
private void initializeParser(JsonParser parser) throws IOException {
  if ( getWrapperKeys().isEmpty() ) {
    return;
  }
  boolean failed = true;
  try {
    String match = parser.skipToKey( getWrapperKeys() );
    Preconditions.checkArgument( match != null && parser.getCurrentToken() != JsonToken.END_OBJECT, "wrapper key(s) not found: %s", getWrapperKeys() );
    failed = false;
  } finally {
    if ( failed ) {
      parser.close();
    }
  }
}
 
开发者ID:icoretech,项目名称:audiobox-jlib,代码行数:21,代码来源:AudioBoxObjectParser.java

示例6: UserInfo

import com.google.api.client.json.JsonParser; //导入依赖的package包/类
UserInfo(JsonParser parser) throws IOException {
    while(parser.nextToken() == JsonToken.FIELD_NAME) {
        switch(parser.getCurrentName()) {
            case "id": parser.nextToken(); id = parser.getText(); break;
            case "email": parser.nextToken(); email = parser.getText(); break;
            case "verified_email": parser.nextToken(); verifiedEmail = parser.getText().equals("true"); break;
            case "name": parser.nextToken(); name = parser.getText(); break;
            case "given_name": parser.nextToken(); givenName = parser.getText(); break;
            case "family_name": parser.nextToken(); familyName = parser.getText(); break;
            case "picture": parser.nextToken(); picture = parser.getText(); break;
            case "locale": parser.nextToken(); locale = parser.getText(); break;
            default: parser.nextToken();
        }
    }
}
 
开发者ID:melchor629,项目名称:agendamlgr,代码行数:16,代码来源:OAuthCallbackServlet.java

示例7: exchangeAuthorizationForToken

import com.google.api.client.json.JsonParser; //导入依赖的package包/类
public OauthToken exchangeAuthorizationForToken(String code, String clientId, String clientSecret, Map<String, Object> options) throws DnsimpleException, IOException {
  Map<String, Object> attributes = new HashMap<String, Object>();
  attributes.put("code", code);
  attributes.put("client_id", clientId);
  attributes.put("client_secret", clientSecret);
  attributes.put("grant_type", "authorization_code");

  if (options.containsKey("state")) {
    attributes.put("state", options.remove("state"));
  }

  if (options.containsKey("redirect_uri")) {
    attributes.put("redirect_uri", options.remove("redirect_uri"));
  }

  HttpResponse response = client.post("oauth/access_token", attributes);
  InputStream in = response.getContent();
  if (in == null) {
    throw new DnsimpleException("Response was empty", null, response.getStatusCode());
  } else {
    try {
      JsonParser jsonParser = GsonFactory.getDefaultInstance().createJsonParser(in);
      return jsonParser.parse(OauthToken.class);
    } finally {
      in.close();
    }
  }
}
 
开发者ID:dnsimple,项目名称:dnsimple-java,代码行数:29,代码来源:OauthEndpoint.java

示例8: expectClient

import com.google.api.client.json.JsonParser; //导入依赖的package包/类
/**
 * Return a Client that is configured to expect a specific URL, HTTP method, request attributes, and HTTP headers.
 *
 * @param expectedUrl The URL string that is expected
 * @param expectedMethod The HTTP method String that is expected
 * @param expectedHeaders a Map<String, Object> of headers
 * @param expectedAttributes A map of values as attributes
 * @return The Client instance
 */
public Client expectClient(final String expectedUrl, final String expectedMethod, final Map<String, Object> expectedHeaders, final Object expectedAttributes) {
  Client client = new Client();

  HttpTransport transport = new MockHttpTransport() {
    @Override
    public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
      assertEquals(new GenericUrl(expectedUrl), new GenericUrl(url));
      assertEquals(expectedMethod, method);

      return new MockLowLevelHttpRequest() {
        @Override
        public LowLevelHttpResponse execute() throws IOException {
          if (!getContentAsString().equals("")) {
            JsonParser jsonParser = GsonFactory.getDefaultInstance().createJsonParser(getContentAsString());
            Map<String,Object> attributes = jsonParser.parse(GenericJson.class);
            assertEquals(expectedAttributes, attributes);
          }

          for (Map.Entry<String, Object> expectedHeader : expectedHeaders.entrySet()) {
            assertEquals(expectedHeader.getValue(), getHeaders().get(expectedHeader.getKey()));
          }

          MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
          return mockResponse(response, resource("pages-1of3.http"));
        }
      };
    }
  };

  client.setTransport(transport);

  return client;
}
 
开发者ID:dnsimple,项目名称:dnsimple-java,代码行数:43,代码来源:DnsimpleTestBase.java

示例9: doPost

import com.google.api.client.json.JsonParser; //导入依赖的package包/类
@Override
@SuppressWarnings("unchecked")
public final void doPost(final HttpServletRequest req,
                         final HttpServletResponse resp)
        throws IOException {
    // Validating unique subscription token before processing the message
    String subscriptionToken = System.getProperty(
            Constants.BASE_PACKAGE + ".subscriptionUniqueToken");
    if (!subscriptionToken.equals(req.getParameter("token"))) {
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        resp.getWriter().close();
        return;
    }

    ServletInputStream inputStream = req.getInputStream();

    // Parse the JSON message to the POJO model class
    JsonParser parser = JacksonFactory.getDefaultInstance()
            .createJsonParser(inputStream);
    parser.skipToKey("message");
    PubsubMessage message = parser.parseAndClose(PubsubMessage.class);

    // Store the message in the datastore
    Entity messageToStore = new Entity("PubsubMessage");
    messageToStore.setProperty("message",
            new String(message.decodeData(), "UTF-8"));
    messageToStore.setProperty("receipt-time", System.currentTimeMillis());
    DatastoreService datastore =
            DatastoreServiceFactory.getDatastoreService();
    datastore.put(messageToStore);

    // Invalidate the cache
    MemcacheService memcacheService =
            MemcacheServiceFactory.getMemcacheService();
    memcacheService.delete(Constants.MESSAGE_CACHE_KEY);

    // Acknowledge the message by returning a success code
    resp.setStatus(HttpServletResponse.SC_OK);
    resp.getWriter().close();
}
 
开发者ID:GoogleCloudPlatform,项目名称:cloud-pubsub-samples-java,代码行数:41,代码来源:ReceiveMessageServlet.java

示例10: instance

import com.google.api.client.json.JsonParser; //导入依赖的package包/类
public static Instance instance(String resourcePath) {
    JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    try {
        JsonParser parser = jsonFactory
                .createJsonParser(new FileInputStream(Resources.getResource(resourcePath).getFile()));
        return parser.parse(Instance.class);
    } catch (Exception e) {
        throw new RuntimeException("failed to load Instance json file " + resourcePath + ": " + e.getMessage(), e);
    }
}
 
开发者ID:elastisys,项目名称:scale.cloudpool,代码行数:11,代码来源:TestInstanceToMachine.java

示例11: parseAndClose

import com.google.api.client.json.JsonParser; //导入依赖的package包/类
/**
 * {@inheritDoc}
 */
@Override
public Object parseAndClose(InputStream in, Charset charset, Type dataType) throws IOException {
  JsonParser parser = getJsonFactory().createJsonParser( in, charset );
  initializeParser( parser );
  return parser.parse( dataType, true, customParser );
}
 
开发者ID:icoretech,项目名称:audiobox-jlib,代码行数:10,代码来源:AudioBoxObjectParser.java

示例12: onSuccess

import com.google.api.client.json.JsonParser; //导入依赖的package包/类
@Override
protected void onSuccess(HttpServletRequest req, HttpServletResponse resp, Credential credential) throws IOException {
    //https://coderanch.com/t/542459/java/GoogleAPI-user-info
    //https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=%ACCESS_TOKEN%
    HttpClient httpClient = new DefaultHttpClient();
    HttpUriRequest request = new HttpGet("https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token="+credential.getAccessToken());
    HttpResponse res = httpClient.execute(request);

    JsonParser parser = JacksonFactory.getDefaultInstance().createJsonParser(res.getEntity().getContent());
    parser.nextToken();
    UserInfo u = new UserInfo(parser);
    parser.close();

    Usuario usuario = usuarioFacade.find(u.id);
    boolean newcomer = false;
    if(usuario == null) {
        newcomer = true;
        usuario = new Usuario();
        usuario.setId(u.id);
        usuario.setNombre(u.givenName);
        usuario.setApellidos(u.familyName);
        usuario.setEmail(u.email);
        usuario.setTipo((short) 1); //By default, will be registering with type 1 (normal user)
        usuario.setImagen(u.picture);
        usuarioFacade.create(usuario);
    } else {
        //If the user has changed something, reflect that into the DB
        usuario.setNombre(u.givenName);
        usuario.setApellidos(u.familyName);
        usuario.setEmail(u.email);
        usuario.setImagen(u.picture);
        usuarioFacade.edit(usuario);
    }

    String token = TokensUtils.createJwtTokenForUserId(u.id);
    String callbackUrl = (String) req.getSession().getAttribute("callbackUrl");
    if(callbackUrl != null) {
        //If we stored the callback URL during the process, return it
        resp.sendRedirect(callbackUrl + "?token=" + token + "&newcomer=" + newcomer);
        req.getSession().removeAttribute("callbackUrl");
    } else {
        //Otherwise, return a json with the same info
        resp.setContentType("application/json");
        resp.setHeader("access-control-allow-origin", "*");
        resp.getOutputStream().print("{\"token\": \"" + token + "\", \"newcomer\": " + newcomer + "}"); //Token
        resp.getOutputStream().close();
    }
}
 
开发者ID:melchor629,项目名称:agendamlgr,代码行数:49,代码来源:OAuthCallbackServlet.java

示例13: main

import com.google.api.client.json.JsonParser; //导入依赖的package包/类
public static void main(String[] args) throws Exception {
  Pubsub client = ServiceAccountConfiguration.createPubsubClient(
      Settings.getSettings().getServiceAccountEmail(),
      Settings.getSettings().getServiceAccountP12KeyPath());
  
  ensureSubscriptionExists(client);
  
  // Kicking off HttpServer which will listen on the specified port and process all
  // incoming push pub/sub notifications
  HttpServer server = HttpServer.create(new InetSocketAddress(
      Settings.getSettings().getPort()), 0);
  
  server.createContext("/", new HttpHandler() {
    public void handle(HttpExchange httpExchange) throws IOException {
      String rawRequest = CharStreams.toString(
          new InputStreamReader(httpExchange.getRequestBody()));
      LOG.info("Raw request: " + rawRequest);

      try {
        JsonParser parser = JacksonFactory.getDefaultInstance().createJsonParser(rawRequest);
        parser.skipToKey(MESSAGE_FIELD);

        PubsubMessage message = parser.parseAndClose(PubsubMessage.class);
        LOG.info("Pubsub message received: " + message.toPrettyString());

        // Decode Protocol Buffer message from base64 encoded byte array.
        EmmPubsub.MdmPushNotification mdmPushNotification = EmmPubsub.MdmPushNotification
            .newBuilder()
            .mergeFrom(message.decodeData())
            .build();

        LOG.info("Message received: " + mdmPushNotification.toString());
      } catch (InvalidProtocolBufferException e) {
        LOG.log(Level.WARNING, "Error occured when decoding message", e);
      }

      // CloudPubSub will interpret 2XX as ACK, anything that isn't 2XX will trigger a retry
      httpExchange.sendResponseHeaders(HttpStatusCodes.STATUS_CODE_NO_CONTENT, 0);
      httpExchange.close();
    }
  });

  server.setExecutor(null);
  server.start(); // Will keep running until killed
}
 
开发者ID:google,项目名称:play-work,代码行数:46,代码来源:PushSubscriber.java


注:本文中的com.google.api.client.json.JsonParser类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。