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


Java ObjectMapper类代码示例

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


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

示例1: search

import org.codehaus.jackson.map.ObjectMapper; //导入依赖的package包/类
public String search(String query) {
    try {
        String url = "?text=" + Utility.urlEncode(query) + "&confidence=" + confidence;
        HttpGet httpGet = new HttpGet(URL + url);
        httpGet.addHeader("Accept", "application/json");
        HttpResponse response = client.execute(httpGet);

        // Error Scenario
        if(response.getStatusLine().getStatusCode() >= 400) {
            logger.error("Spotlight Service could not answer due to: " + response.getStatusLine());
            return null;
        }
        else {
            String entities = EntityUtils.toString(response.getEntity());
            JsonNode entity = new ObjectMapper().readTree(entities).get("Resources").get(0);
            return entity.get("@URI").getTextValue();
        }
    }
    catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
 
开发者ID:dbpedia,项目名称:chatbot,代码行数:24,代码来源:SpotlightService.java

示例2: logResponse

import org.codehaus.jackson.map.ObjectMapper; //导入依赖的package包/类
/**
 * Logs an RPC response to the LOG file, producing valid JSON objects for client Operations.
 *
 * @param params The parameters received in the call.
 * @param methodName The name of the method invoked
 * @param call The string representation of the call
 * @param tag The tag that will be used to indicate this event in the log.
 * @param startTime The time that the call was initiated, in ms.
 * @param processingTime The duration that the call took to run, in ms.
 * @param qTime The duration that the call spent on the queue prior to being initiated, in ms.
 * @param responseSize The size in bytes of the response buffer.
 */
void logResponse(Object[] params, String methodName, String call, String tag, long startTime,
    int processingTime, int qTime, long responseSize) throws IOException {
  // for JSON encoding
  ObjectMapper mapper = new ObjectMapper();
  // base information that is reported regardless of type of call
  Map<String, Object> responseInfo = new HashMap<String, Object>();
  responseInfo.put("starttimems", startTime);
  responseInfo.put("processingtimems", processingTime);
  responseInfo.put("queuetimems", qTime);
  responseInfo.put("responsesize", responseSize);
  responseInfo.put("class", instance.getClass().getSimpleName());
  responseInfo.put("method", methodName);
  responseInfo.put("call", call);
  /*
   * LOG.warn("(response" + tag + "): " + mapper.writeValueAsString(responseInfo));
   */
}
 
开发者ID:Tencent,项目名称:angel,代码行数:30,代码来源:ProtobufRpcEngine.java

示例3: testScanningUnknownColumnJson

import org.codehaus.jackson.map.ObjectMapper; //导入依赖的package包/类
@Test
public void testScanningUnknownColumnJson() throws IOException, JAXBException {
  // Test scanning particular columns with limit.
  StringBuilder builder = new StringBuilder();
  builder.append("/*");
  builder.append("?");
  builder.append(Constants.SCAN_COLUMN + "=a:test");
  Response response = client.get("/" + TABLE  + builder.toString(),
    Constants.MIMETYPE_JSON);
  assertEquals(200, response.getCode());
  assertEquals(Constants.MIMETYPE_JSON, response.getHeader("content-type"));
  ObjectMapper mapper = new JacksonProvider().locateMapper(CellSetModel.class,
    MediaType.APPLICATION_JSON_TYPE);
  CellSetModel model = mapper.readValue(response.getStream(), CellSetModel.class);
  int count = TestScannerResource.countCellSet(model);
  assertEquals(0, count);
}
 
开发者ID:fengchen8086,项目名称:ditb,代码行数:18,代码来源:TestTableScan.java

示例4: parseResponse

import org.codehaus.jackson.map.ObjectMapper; //导入依赖的package包/类
@Override
public ReadAggregateResult parseResponse(HttpResponse response, ObjectMapper mapper) throws IOException, PyroclastAPIException {
    int status = response.getStatusLine().getStatusCode();

    switch (status) {
        case 200:
            HttpEntity entity = response.getEntity();
            StringWriter writer = new StringWriter();
            IOUtils.copy(entity.getContent(), writer, "UTF-8");
            String json = writer.toString();

            return mapper.readValue(json, ReadAggregateResult.class);
        case 400:
            throw new MalformedEventException();

        case 401:
            throw new UnauthorizedAccessException();

        default:
            throw new UnknownAPIException(response.getStatusLine().toString());
    }
}
 
开发者ID:PyroclastIO,项目名称:pyroclast-java,代码行数:23,代码来源:ReadAggregateParser.java

示例5: updateAppTemplatesWhenDeployToJvmsChanged

import org.codehaus.jackson.map.ObjectMapper; //导入依赖的package包/类
private void updateAppTemplatesWhenDeployToJvmsChanged(final ResourceIdentifier resourceIdentifier, final String resourceName, final String previousMetaData, final String updatedMetaData) {
    try {
        ResourceTemplateMetaData oldMetaData = new ObjectMapper().readValue(previousMetaData, ResourceTemplateMetaData.class);
        ResourceTemplateMetaData newMetaData = new ObjectMapper().readValue(updatedMetaData, ResourceTemplateMetaData.class);
        boolean previousDeployToJvms = oldMetaData.getEntity().getDeployToJvms();
        boolean newDeployToJvms = newMetaData.getEntity().getDeployToJvms();
        if (previousDeployToJvms != newDeployToJvms) {
            Group group = groupPersistenceService.getGroup(resourceIdentifier.groupName);
            if (newDeployToJvms) {
                // deployToJvms was changed to true - need to create the JVM templates
                JpaGroupAppConfigTemplate appTemplate = resourceDao.getGroupLevelAppResource(resourceName, resourceIdentifier.webAppName, resourceIdentifier.groupName);
                newMetaData.setJsonData(updatedMetaData);
                createJvmTemplateFromAppResource(resourceIdentifier, appTemplate.getTemplateContent(), newMetaData, group);
            } else {
                // deployToJvms was to false - need to delete the JVM templates
                for (Jvm jvm : group.getJvms()) {
                    resourceDao.deleteAppResource(resourceName, resourceIdentifier.webAppName, jvm.getJvmName());
                }
            }
        }
    } catch (IOException ioe) {
        final String errorMsg = MessageFormat.format("Failed to parse meta data for war {0} in application {1} during an update of the meta data", resourceName, resourceIdentifier.webAppName);
        LOGGER.error(errorMsg, ioe);
        throw new GroupLevelAppResourceHandlerException(errorMsg);
    }
}
 
开发者ID:cerner,项目名称:jwala,代码行数:27,代码来源:GroupLevelAppResourceHandler.java

示例6: createServletExceptionResponse

import org.codehaus.jackson.map.ObjectMapper; //导入依赖的package包/类
/**
 * Creates a HTTP servlet response serializing the exception in it as JSON.
 *
 * @param response the servlet response
 * @param status the error code to set in the response
 * @param ex the exception to serialize in the response
 * @throws IOException thrown if there was an error while creating the
 * response
 */
public static void createServletExceptionResponse(
    HttpServletResponse response, int status, Throwable ex)
    throws IOException {
  response.setStatus(status);
  response.setContentType(APPLICATION_JSON_MIME);
  Map<String, Object> json = new LinkedHashMap<String, Object>();
  json.put(ERROR_MESSAGE_JSON, getOneLineMessage(ex));
  json.put(ERROR_EXCEPTION_JSON, ex.getClass().getSimpleName());
  json.put(ERROR_CLASSNAME_JSON, ex.getClass().getName());
  Map<String, Object> jsonResponse = new LinkedHashMap<String, Object>();
  jsonResponse.put(ERROR_JSON, json);
  ObjectMapper jsonMapper = new ObjectMapper();
  Writer writer = response.getWriter();
  jsonMapper.writerWithDefaultPrettyPrinter().writeValue(writer, jsonResponse);
  writer.flush();
}
 
开发者ID:nucypher,项目名称:hadoop-oss,代码行数:26,代码来源:HttpExceptionUtils.java

示例7: deserialize

import org.codehaus.jackson.map.ObjectMapper; //导入依赖的package包/类
@Override
public StatePair deserialize(JsonParser parser, 
                             DeserializationContext context)
throws IOException, JsonProcessingException {
  ObjectMapper mapper = (ObjectMapper) parser.getCodec();
  // set the state-pair object tree
  ObjectNode statePairObject = (ObjectNode) mapper.readTree(parser);
  Class<?> stateClass = null;
  
  try {
    stateClass = 
      Class.forName(statePairObject.get("className").getTextValue().trim());
  } catch (ClassNotFoundException cnfe) {
    throw new RuntimeException("Invalid classname!", cnfe);
  }
  
  String stateJsonString = statePairObject.get("state").toString();
  State state = (State) mapper.readValue(stateJsonString, stateClass);
  
  return new StatePair(state);
}
 
开发者ID:naver,项目名称:hadoop,代码行数:22,代码来源:StateDeserializer.java

示例8: DifficultyTestSuite

import org.codehaus.jackson.map.ObjectMapper; //导入依赖的package包/类
public DifficultyTestSuite(String json) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    JavaType type = mapper.getTypeFactory().
            constructMapType(HashMap.class, String.class, DifficultyTestCase.class);

    Map<String, DifficultyTestCase> caseMap = new ObjectMapper().readValue(json, type);

    for (Map.Entry<String, DifficultyTestCase> e : caseMap.entrySet()) {
        e.getValue().setName(e.getKey());
        testCases.add(e.getValue());
    }

    Collections.sort(testCases, new Comparator<DifficultyTestCase>() {
        @Override
        public int compare(DifficultyTestCase t1, DifficultyTestCase t2) {
            return t1.getName().compareTo(t2.getName());
        }
    });
}
 
开发者ID:Aptoide,项目名称:AppCoins-ethereumj,代码行数:20,代码来源:DifficultyTestSuite.java

示例9: listStatus

import org.codehaus.jackson.map.ObjectMapper; //导入依赖的package包/类
/**
 * Return the JSON formatted list of the files in the specified directory.
 * @param path a path specifies a directory to list
 * @return JSON formatted file list in the directory
 * @throws IOException if failed to serialize fileStatus to JSON.
 */
String listStatus(String path) throws IOException {
  StringBuilder sb = new StringBuilder();
  ObjectMapper mapper = new ObjectMapper();
  List<Map<String, Object>> fileStatusList = getFileStatusList(path);
  sb.append("{\"FileStatuses\":{\"FileStatus\":[\n");
  int i = 0;
  for (Map<String, Object> fileStatusMap : fileStatusList) {
    if (i++ != 0) {
      sb.append(',');
    }
    sb.append(mapper.writeValueAsString(fileStatusMap));
  }
  sb.append("\n]}}\n");
  return sb.toString();
}
 
开发者ID:naver,项目名称:hadoop,代码行数:22,代码来源:FSImageLoader.java

示例10: toXAttrNames

import org.codehaus.jackson.map.ObjectMapper; //导入依赖的package包/类
public static List<String> toXAttrNames(final Map<?, ?> json)
    throws IOException {
  if (json == null) {
    return null;
  }

  final String namesInJson = (String) json.get("XAttrNames");
  ObjectReader reader = new ObjectMapper().reader(List.class);
  final List<Object> xattrs = reader.readValue(namesInJson);
  final List<String> names =
    Lists.newArrayListWithCapacity(json.keySet().size());

  for (Object xattr : xattrs) {
    names.add((String) xattr);
  }
  return names;
}
 
开发者ID:naver,项目名称:hadoop,代码行数:18,代码来源:JsonUtil.java

示例11: parseResponse

import org.codehaus.jackson.map.ObjectMapper; //导入依赖的package包/类
@Override
public ProducedEventsResult parseResponse(HttpResponse response, ObjectMapper mapper) throws IOException, PyroclastAPIException {
    int status = response.getStatusLine().getStatusCode();

    switch (status) {
        case 200:
            HttpEntity entity = response.getEntity();
            StringWriter writer = new StringWriter();
            IOUtils.copy(entity.getContent(), writer, "UTF-8");
            String json = writer.toString();

            return mapper.readValue(json, ProducedEventsResult.class);
        case 400:
            throw new MalformedEventException();

        case 401:
            throw new UnauthorizedAccessException();

        default:
            throw new UnknownAPIException(response.getStatusLine().toString());
    }
}
 
开发者ID:PyroclastIO,项目名称:pyroclast-java,代码行数:23,代码来源:BulkProduceEventsParser.java

示例12: testValidateResponseJsonErrorUnknownException

import org.codehaus.jackson.map.ObjectMapper; //导入依赖的package包/类
@Test
public void testValidateResponseJsonErrorUnknownException()
    throws IOException {
  Map<String, Object> json = new HashMap<String, Object>();
  json.put(HttpExceptionUtils.ERROR_EXCEPTION_JSON, "FooException");
  json.put(HttpExceptionUtils.ERROR_CLASSNAME_JSON, "foo.FooException");
  json.put(HttpExceptionUtils.ERROR_MESSAGE_JSON, "EX");
  Map<String, Object> response = new HashMap<String, Object>();
  response.put(HttpExceptionUtils.ERROR_JSON, json);
  ObjectMapper jsonMapper = new ObjectMapper();
  String msg = jsonMapper.writeValueAsString(response);
  InputStream is = new ByteArrayInputStream(msg.getBytes());
  HttpURLConnection conn = Mockito.mock(HttpURLConnection.class);
  Mockito.when(conn.getErrorStream()).thenReturn(is);
  Mockito.when(conn.getResponseMessage()).thenReturn("msg");
  Mockito.when(conn.getResponseCode()).thenReturn(
      HttpURLConnection.HTTP_BAD_REQUEST);
  try {
    HttpExceptionUtils.validateResponse(conn, HttpURLConnection.HTTP_CREATED);
    Assert.fail();
  } catch (IOException ex) {
    Assert.assertTrue(ex.getMessage().contains("EX"));
    Assert.assertTrue(ex.getMessage().contains("foo.FooException"));
  }
}
 
开发者ID:naver,项目名称:hadoop,代码行数:26,代码来源:TestHttpExceptionUtils.java

示例13: getMessage

import org.codehaus.jackson.map.ObjectMapper; //导入依赖的package包/类
public static List<Message> getMessage( String response )
{
    ObjectMapper mapper = new ObjectMapper();
    List<Message> messages = null;
    try
    {
        messages = mapper.readValue( response, new TypeReference<List<Message>>()
        {
        } );
    }
    catch ( IOException e )
    {
        e.printStackTrace();
    }
    return messages;
}
 
开发者ID:oncecloud,项目名称:devops-cstack,代码行数:17,代码来源:JsonConverter.java

示例14: countersToJSON

import org.codehaus.jackson.map.ObjectMapper; //导入依赖的package包/类
@Private
public JsonNode countersToJSON(Counters counters) {
  ObjectMapper mapper = new ObjectMapper();
  ArrayNode nodes = mapper.createArrayNode();
  if (counters != null) {
    for (CounterGroup counterGroup : counters) {
      ObjectNode groupNode = nodes.addObject();
      groupNode.put("NAME", counterGroup.getName());
      groupNode.put("DISPLAY_NAME", counterGroup.getDisplayName());
      ArrayNode countersNode = groupNode.putArray("COUNTERS");
      for (Counter counter : counterGroup) {
        ObjectNode counterNode = countersNode.addObject();
        counterNode.put("NAME", counter.getName());
        counterNode.put("DISPLAY_NAME", counter.getDisplayName());
        counterNode.put("VALUE", counter.getValue());
      }
    }
  }
  return nodes;
}
 
开发者ID:naver,项目名称:hadoop,代码行数:21,代码来源:JobHistoryEventHandler.java

示例15: parseResponse

import org.codehaus.jackson.map.ObjectMapper; //导入依赖的package包/类
@Override
public ReadCommitResult parseResponse(HttpResponse response, ObjectMapper mapper) throws IOException, PyroclastAPIException {
    int status = response.getStatusLine().getStatusCode();

    switch (status) {
        case 200:
            return new ReadCommitResult(true);
        case 400:
            throw new MalformedEventException();

        case 401:
            throw new UnauthorizedAccessException();

        default:
            throw new UnknownAPIException(response.getStatusLine().toString());
    }
}
 
开发者ID:PyroclastIO,项目名称:pyroclast-java,代码行数:18,代码来源:ReadCommitParser.java


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