Java Code Examples for org.codehaus.jackson.JsonParseException

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project uaa, under directory /common/src/main/java/org/cloudfoundry/identity/uaa/scim/json/.

Source file: JsonDateDeserializer.java

  24 
vote

@Override public Date deserialize(JsonParser parser,DeserializationContext context) throws IOException, JsonProcessingException {
  try {
    return dateFormat.parse(parser.getText());
  }
 catch (  ParseException e) {
    throw new JsonParseException("Could not parse date",parser.getCurrentLocation(),e);
  }
}
 

Example 2

From project com.cedarsoft.serialization, under directory /jackson/src/main/java/com/cedarsoft/serialization/jackson/.

Source file: AbstractJacksonSerializer.java

  23 
vote

@Deprecated public static void ensureParserClosed(@Nonnull JsonParser parser) throws IOException {
  if (parser.nextToken() != null) {
    throw new JsonParseException("No consumed everything " + parser.getCurrentToken(),parser.getCurrentLocation());
  }
  parser.close();
}
 

Example 3

From project ACLS-protocol-library, under directory /aclslib/src/main/java/au/edu/uq/cmm/aclslib/config/.

Source file: JsonConfigLoader.java

  21 
vote

/** 
 * Read the configuration from an input stream
 * @param configFile
 * @return the configuration or null if there was a problem reading.
 * @throws ConfigurationException 
 */
public C readConfiguration(InputStream is) throws ConfigurationException {
  try {
    ObjectMapper mapper=new ObjectMapper();
    C res=mapper.readValue(is,clazz);
    return res;
  }
 catch (  JsonParseException ex) {
    throw new ConfigurationException("The input is not valid JSON",ex);
  }
catch (  JsonMappingException ex) {
    throw new ConfigurationException("The input JSON doesn't match " + "the " + clazz.getCanonicalName() + " class",ex);
  }
catch (  IOException ex) {
    throw new ConfigurationException("IO error while reading the JSON",ex);
  }
}
 

Example 4

From project akela, under directory /src/main/java/com/mozilla/pig/eval/json/.

Source file: MapToJson.java

  21 
vote

@SuppressWarnings("unchecked") @Override public String exec(Tuple input) throws IOException {
  if (input == null || input.size() == 0) {
    return null;
  }
  try {
    String json=jsonMapper.writeValueAsString((Map<String,Object>)input.get(0));
    return json;
  }
 catch (  JsonParseException e) {
    pigLogger.warn(this,"JSON Parse Error",ERRORS.JSONParseError);
  }
catch (  JsonMappingException e) {
    pigLogger.warn(this,"JSON Mapping Error",ERRORS.JSONMappingError);
  }
  return null;
}
 

Example 5

From project ALP, under directory /workspace/alp-utils/src/main/java/com/lohika/alp/utils/json/validator/.

Source file: ALPJSONValidator.java

  21 
vote

/** 
 * This function recursively goes over all elements in JSON and answer if each one is correct.
 * @param feedObj - JsonNode object that currently under verification
 * @param parentName - name of parent of current element
 * @param schemaStack - Linked List that store list of currently read schemas
 * @return true, if successful
 * @throws JsonParseException the json parse exception
 * @throws FileNotFoundException the file not found exception
 * @throws IOException Signals that an I/O exception has occurred.
 */
private boolean validateObject(JsonNode feedObj,String parentName,LinkedList<String> schemaStack) throws JsonParseException, FileNotFoundException, IOException {
  Iterator<JsonNode> Inode=feedObj.getElements();
  Iterator<String> Istring=feedObj.getFieldNames();
  while (Inode.hasNext()) {
    String str=Istring.next();
    JsonNode nod=Inode.next();
    JSONStack.add(str);
    LinkedList<String> t_schemaStack=new LinkedList<String>();
    t_schemaStack.addAll(schemaStack);
    LinkedList<JSONTypes> TypesList=getItemTypeFromSchema(str,parentName,new LinkedList<String>(),t_schemaStack);
    if (TypesList == null)     ErrorsStack.add("'" + GeneratePath() + "' not belongs to '"+ parentName+ "'");
 else {
      JSONTypes realType=detectType(TypesList,nod);
      if (realType == JSONTypes.object) {
        LinkedList<String> t_SchemaStack2=new LinkedList<String>();
        t_SchemaStack2.addAll(t_schemaStack);
        validateObject(nod,str,t_SchemaStack2);
      }
 else       if (realType == JSONTypes.array) {
        LinkedList<String> t_SchemaStack2=new LinkedList<String>();
        t_SchemaStack2.addAll(t_schemaStack);
        validateArray(nod,str,t_SchemaStack2);
      }
 else       if (realType == JSONTypes.string && nod.getTextValue().isEmpty())       ErrorsStack.add("Item '" + GeneratePath() + "' is empty");
    }
    JSONStack.removeLast();
  }
  if (ErrorsStack.isEmpty())   return true;
 else   return false;
}
 

Example 6

From project Arecibo, under directory /collector-client-support/src/main/java/com/ning/arecibo/collector/rest/.

Source file: DefaultCollectorClient.java

  19 
vote

private <T>T readValue(final InputStream stream,final TypeReference<T> valueTypeRef){
  try {
    return mapper.<T>readValue(stream,valueTypeRef);
  }
 catch (  JsonMappingException e) {
    log.warn("Failed to map response from collector",e);
  }
catch (  JsonParseException e) {
    log.warn("Failed to parse response from collector",e);
  }
catch (  IOException e) {
    log.warn("Generic I/O Exception from collector",e);
  }
 finally {
    if (stream != null) {
      try {
        stream.close();
      }
 catch (      IOException e) {
        log.warn("Failed to close http-client - provided InputStream",e);
      }
    }
  }
  return null;
}
 

Example 7

From project arquillian-extension-persistence, under directory /impl/src/main/java/org/jboss/arquillian/persistence/dbunit/dataset/json/.

Source file: JsonDataSetProducer.java

  19 
vote

@Override Map<String,List<Map<String,String>>> loadDataSet() throws DataSetException {
  Map<String,List<Map<String,String>>> dataset=Collections.emptyMap();
  try {
    dataset=new ObjectMapper().readValue(input,Map.class);
  }
 catch (  JsonParseException e) {
    throw new DataSetException("Error parsing json data set",e);
  }
catch (  JsonMappingException e) {
    throw new DataSetException("Error mapping json data set",e);
  }
catch (  IOException e) {
    throw new DataSetException("Error opening json data set",e);
  }
  return dataset;
}
 

Example 8

From project avro, under directory /lang/java/avro/src/main/java/org/apache/avro/.

Source file: Schema.java

  19 
vote

private Schema parse(JsonParser parser) throws IOException {
  boolean saved=validateNames.get();
  try {
    validateNames.set(validate);
    return Schema.parse(MAPPER.readTree(parser),names);
  }
 catch (  JsonParseException e) {
    throw new SchemaParseException(e);
  }
 finally {
    validateNames.set(saved);
  }
}
 

Example 9

From project candlepin, under directory /src/main/java/org/candlepin/audit/.

Source file: ActivationListener.java

  19 
vote

@Override public void onEvent(Event e){
  if (e.getType().equals(Event.Type.CREATED) && e.getTarget().equals(Event.Target.POOL)) {
    String poolJson=e.getNewEntity();
    Reader reader=new StringReader(poolJson);
    try {
      Pool pool=mapper.readValue(reader,Pool.class);
      subscriptionService.sendActivationEmail(pool.getSubscriptionId());
    }
 catch (    JsonMappingException ex) {
      logError(e);
    }
catch (    JsonParseException ex) {
      logError(e);
    }
catch (    IOException ex) {
      logError(e);
    }
  }
}
 

Example 10

From project cloudify, under directory /esc/src/main/java/org/cloudifysource/esc/driver/provisioning/openstack/.

Source file: RSCloudDriver.java

  19 
vote

@SuppressWarnings("unchecked") private String getAutenticationTokenIdFromResponse(final String resp){
  final ObjectMapper mapper=new ObjectMapper();
  try {
    Map<String,Object> readValue=mapper.readValue(new StringReader(resp),Map.class);
    Map<String,Object> accessMap=(Map<String,Object>)readValue.get("access");
    Map<String,String> tokenMap=(Map<String,String>)accessMap.get("token");
    String tokenId=tokenMap.get("id");
    return tokenId;
  }
 catch (  JsonParseException e) {
    throw new RuntimeException(e);
  }
catch (  JsonMappingException e) {
    throw new RuntimeException(e);
  }
catch (  IOException e) {
    throw new RuntimeException(e);
  }
}
 

Example 11

From project CMM-data-grabber, under directory /paul/src/main/java/au/edu/uq/cmm/paul/grabber/.

Source file: DatasetMetadata.java

  19 
vote

public void serialize(Writer writer) throws IOException {
  try {
    ObjectMapper mapper=new ObjectMapper();
    JsonFactory jf=new JsonFactory();
    JsonGenerator jg=jf.createJsonGenerator(writer);
    jg.useDefaultPrettyPrinter();
    mapper.writeValue(jg,this);
  }
 catch (  JsonParseException ex) {
    throw new PaulException(ex);
  }
catch (  JsonMappingException ex) {
    throw new PaulException(ex);
  }
}
 

Example 12

From project components-ness-httpclient, under directory /client/src/main/java/com/nesscomputing/httpclient/response/.

Source file: JsonContentConverter.java

  19 
vote

@Override public T convert(final HttpClientResponse httpClientResponse,final InputStream inputStream) throws IOException {
  final int responseCode=httpClientResponse.getStatusCode();
switch (responseCode) {
case 200:
    return objectMapper.<T>readValue(inputStream,typeReference);
case 204:
  return null;
case 201:
try {
  return objectMapper.<T>readValue(inputStream,typeReference);
}
 catch (JsonParseException jpe) {
  LOG.trace(jpe,"while reading response");
  return null;
}
case 404:
if (ignore404) {
return null;
}
default :
LOG.warn("Remote service responded to \"%s\" with code %d (cause: %s)",httpClientResponse.getUri(),responseCode,httpClientResponse.getStatusText());
throw new HttpResponseException(httpClientResponse);
}
}
 

Example 13

From project components-ness-jersey, under directory /jersey/src/main/java/com/nesscomputing/jersey/exceptions/.

Source file: JsonMessageReaderMapper.java

  19 
vote

@Override public Response toResponse(JsonParseException exception){
  for (  StackTraceElement e : exception.getStackTrace()) {
    if (JacksonJsonProvider.class.getName().equals(e.getClassName())) {
      final Map<String,String> response=ImmutableMap.of("code","400","trace",ObjectUtils.toString(MDC.get("track")),"message",ObjectUtils.toString(exception.getMessage(),"(no message)"));
      return Response.status(400).entity(response).type(MediaType.APPLICATION_JSON_TYPE).build();
    }
  }
  return super.toResponse(exception);
}
 

Example 14

From project core_1, under directory /transform/src/main/java/org/switchyard/transform/json/internal/.

Source file: JSON2JavaTransformer.java

  19 
vote

@Override public Message transform(Message message){
  try {
    Object result=_mapper.readValue(message.getContent(Reader.class),_clazz);
    if (_clazz.isInstance(result)) {
      message.setContent(result);
      return message;
    }
 else {
      throw new SwitchYardException("Result of transformation has wrong instance type " + result.getClass());
    }
  }
 catch (  JsonParseException e) {
    throw new SwitchYardException("Unexpected JSON parse exception, check your transformer configuration",e);
  }
catch (  JsonMappingException e) {
    throw new SwitchYardException("Unexpected JSON mapping exception, check your transformer configuration",e);
  }
catch (  IOException e) {
    throw new SwitchYardException("Unexpected I/O exception, check your transformer configuration",e);
  }
}
 

Example 15

From project devoxx-france-android-in-fine, under directory /src/com/infine/android/devoxx/io/json/.

Source file: JsonRoomHandler.java

  19 
vote

/** 
 * From the  {@link InputStream} it returns an {@link RoomsData} object. Yeah !
 * @param input
 * @return
 */
private RoomsData readData(InputStream input){
  RoomsData rooms=null;
  ObjectMapper mapper=MapperFactory.getMapperInstance();
  try {
    rooms=mapper.readValue(input,RoomsData.class);
  }
 catch (  JsonParseException e) {
    Log.e(TAG,"error parsing JSON",e);
  }
catch (  JsonMappingException e) {
    Log.e(TAG,"error mapping JSON",e);
  }
catch (  IOException e) {
    Log.e(TAG,"error when reading the JSON stream",e);
  }
  return rooms;
}
 

Example 16

From project DirectMemory, under directory /server/directmemory-server-commons/src/main/java/org/apache/directmemory/server/commons/.

Source file: DirectMemoryParser.java

  19 
vote

public DirectMemoryRequest buildRequest(InputStream inputStream) throws DirectMemoryException {
  try {
    JsonParser jp=this.jsonFactory.createJsonParser(inputStream);
    DirectMemoryRequest rq=new DirectMemoryRequest();
    JsonToken jsonToken=jp.nextToken();
    while (jsonToken != JsonToken.END_OBJECT && jsonToken != null) {
      String fieldName=jp.getCurrentName();
      if (DirectMemoryConstants.KEY_FIELD_NAME.equals(fieldName)) {
        rq.setKey(jp.getText());
      }
      if (DirectMemoryConstants.PUT_FIELD_NAME.equals(fieldName)) {
        rq.setUpdate(jp.getValueAsBoolean());
      }
      if (DirectMemoryConstants.EXPIRES_IN_FIELD_NAME.equals(fieldName)) {
        rq.setExpiresIn(jp.getValueAsInt());
      }
      if (DirectMemoryConstants.CACHE_CONTENT_FIELD_NAME.equals(fieldName)) {
        jp.nextToken();
        rq.setCacheContent(jp.getBinaryValue());
      }
      jsonToken=jp.nextToken();
    }
    jp.close();
    return rq;
  }
 catch (  JsonParseException e) {
    throw new DirectMemoryException(e.getMessage(),e);
  }
catch (  IOException e) {
    throw new DirectMemoryException(e.getMessage(),e);
  }
}
 

Example 17

From project distributed_loadgen, under directory /src/com/couchbase/loadgen/.

Source file: Config.java

  19 
vote

public void setConfig(String configjson){
  JsonFactory factory=new JsonFactory();
  try {
    JsonParser p=factory.createJsonParser(configjson.getBytes());
    p.nextToken();
    p.nextToken();
    if (p.getCurrentName().equals(PROPERTIES_JSON_ID)) {
      p.nextToken();
      while (p.nextToken() != JsonToken.END_OBJECT) {
        String key=p.getCurrentName();
        JsonToken token=p.nextToken();
        if (token == JsonToken.VALUE_NUMBER_INT && properties.get(key) instanceof Integer) {
          properties.put(key,new Integer(p.getIntValue()));
        }
 else         if (token == JsonToken.VALUE_NUMBER_FLOAT && properties.get(key) instanceof Double) {
          properties.put(key,new Double(p.getDoubleValue()));
        }
 else         if ((token == JsonToken.VALUE_FALSE || token == JsonToken.VALUE_TRUE) && properties.get(key) instanceof Boolean) {
          properties.put(key,new Boolean(p.getBooleanValue()));
        }
 else         if (token == JsonToken.VALUE_STRING && properties.get(key) instanceof String) {
          properties.put(key,p.getText());
        }
 else {
          LOG.error("Field for " + key + " did not match type");
        }
      }
    }
 else {
      LOG.error("Attempted to set an invalid config");
    }
  }
 catch (  JsonParseException e) {
    LOG.error("Attempted to set an invalid config");
  }
catch (  IOException e) {
    LOG.error("Attempted to set an invalid config");
  }
}
 

Example 18

From project dragon, under directory /hadoop-dragon-core/src/main/java/org/apache/hadoop/realtime/.

Source file: DragonJobRunner.java

  19 
vote

@SuppressWarnings("unchecked") private void readTokensFromFiles(Configuration conf,Credentials credentials) throws IOException {
  String binaryTokenFilename=conf.get(DragonJobConfig.DRAGON_JOB_CREDENTIALS_BINARY);
  if (binaryTokenFilename != null) {
    Credentials binary=Credentials.readTokenStorageFile(new Path("file:///" + binaryTokenFilename),conf);
    credentials.addAll(binary);
  }
  String tokensFileName=conf.get(DragonJobConfig.DRAGON_JOB_CREDENTIALS_JSON);
  if (tokensFileName != null) {
    LOG.info("loading user's secret keys from " + tokensFileName);
    String localFileName=new Path(tokensFileName).toUri().getPath();
    boolean json_error=false;
    try {
      ObjectMapper mapper=new ObjectMapper();
      Map<String,String> nm=mapper.readValue(new File(localFileName),Map.class);
      for (      Map.Entry<String,String> ent : nm.entrySet()) {
        credentials.addSecretKey(new Text(ent.getKey()),ent.getValue().getBytes());
      }
    }
 catch (    JsonMappingException e) {
      json_error=true;
    }
catch (    JsonParseException e) {
      json_error=true;
    }
    if (json_error)     LOG.warn("couldn't parse Token Cache JSON file with user secret keys");
  }
}
 

Example 19

From project dynjs, under directory /src/main/java/org/dynjs/runtime/builtins/types/json/.

Source file: Parse.java

  19 
vote

protected Object parse(ExecutionContext context,JsonParser p) throws JsonParseException, IOException {
  JsonToken t=p.getCurrentToken();
  if (t == JsonToken.START_ARRAY) {
    return parseArray(context,p);
  }
 else   if (t == JsonToken.START_OBJECT) {
    return parseObject(context,p);
  }
 else {
    return parseValue(context,p);
  }
}
 

Example 20

From project fast-http, under directory /src/main/java/org/neo4j/smack/serialization/.

Source file: JsonDeserializer.java

  19 
vote

public JsonDeserializer(JsonFactory factory,InputStream stream){
  try {
    this.parser=factory.createJsonParser(stream);
  }
 catch (  JsonParseException e) {
    throw new DeserializationException("Unable to instantiate JSON parser.",e);
  }
catch (  IOException e) {
    e.printStackTrace();
    throw new DeserializationException("Unable to instantiate JSON parser.",e);
  }
}
 

Example 21

From project fastjson, under directory /src/test/java/com/alibaba/json/test/performance/.

Source file: JacksonGroupParser.java

  19 
vote

public static String getNextTextValue(String fieldName,JsonParser parser) throws JsonParseException, IOException {
  JsonToken current=parser.nextToken();
  if (current != JsonToken.FIELD_NAME || !fieldName.equals(parser.getCurrentName())) {
    reportParseError("Error occoured while getting value by field name:" + fieldName,parser.getCurrentLocation());
  }
  current=parser.nextToken();
  return parser.getText();
}
 

Example 22

From project floodlight, under directory /src/main/java/net/floodlightcontroller/firewall/.

Source file: FirewallResource.java

  19 
vote

/** 
 * Extracts subnet mask from a JSON string
 * @param fmJson The JSON formatted string
 * @return The subnet mask
 * @throws IOException If there was an error parsing the JSON
 */
public static String jsonExtractSubnetMask(String fmJson) throws IOException {
  String subnet_mask="";
  MappingJsonFactory f=new MappingJsonFactory();
  JsonParser jp;
  try {
    jp=f.createJsonParser(fmJson);
  }
 catch (  JsonParseException e) {
    throw new IOException(e);
  }
  jp.nextToken();
  if (jp.getCurrentToken() != JsonToken.START_OBJECT) {
    throw new IOException("Expected START_OBJECT");
  }
  while (jp.nextToken() != JsonToken.END_OBJECT) {
    if (jp.getCurrentToken() != JsonToken.FIELD_NAME) {
      throw new IOException("Expected FIELD_NAME");
    }
    String n=jp.getCurrentName();
    jp.nextToken();
    if (jp.getText().equals(""))     continue;
    if (n == "subnet-mask") {
      subnet_mask=jp.getText();
      break;
    }
  }
  return subnet_mask;
}
 

Example 23

From project geolatte-common, under directory /src/main/java/org/geolatte/common/dataformats/json/jackson/.

Source file: JsonMapper.java

  19 
vote

/** 
 * Converts a given string into an object of the given class.
 * @param clazz      The class to which the returned object should belong
 * @param jsonString the jsonstring representing the object to be parsed
 * @param < T >        the type of the returned object
 * @return an instantiated object of class T corresponding to the given jsonstring
 * @throws JsonException If deserialization failed or if the object of class T could for some reason not beconstructed.
 */
public synchronized <T>T fromJson(String jsonString,Class<T> clazz) throws JsonException {
  if (jsonString == null) {
    return null;
  }
  Reader reader=new StringReader(jsonString);
  try {
    return mapper.readValue(reader,clazz);
  }
 catch (  JsonParseException e) {
    throw new JsonException(e.getMessage(),e);
  }
catch (  JsonMappingException e) {
    throw new JsonException(e.getMessage(),e);
  }
catch (  IOException e) {
    throw new JsonException(e.getMessage(),e);
  }
}
 

Example 24

From project gnip4j, under directory /core/src/test/java/com/zaubersoftware/gnip4j/http/.

Source file: JSONDeserializationTest.java

  19 
vote

@Test public void testDeserializeWithPolygonAndPoint() throws JsonParseException, IOException {
  final InputStream is=getClass().getClassLoader().getResourceAsStream("com/zaubersoftware/gnip4j/payload/deserialize/geolocated-tweets.json");
  try {
    final JsonParser parser=mapper.getJsonFactory().createJsonParser(is);
    final Activities activities=parser.readValueAs(Activities.class);
    Geo geo1=activities.getActivities().get(0).getGeo();
    Geo geo2=activities.getActivities().get(1).getGeo();
    Geo geo3=activities.getActivities().get(0).getLocation().getGeo();
    Geo geo4=activities.getActivities().get(1).getLocation().getGeo();
    assertNull(geo1);
    assertEquals("lat: 35.11222481 lon: -78.99696934",geo2.getCoordinates().toString());
    assertEquals("[[ lat: -0.5093057 lon: 51.286606 ][ lat: 0.334433 lon: 51.286606 ][ lat: 0.334433 lon: 51.691672 ][ lat: -0.5093057 lon: 51.691672 ]]",geo3.getCoordinates().toString());
    assertEquals("[[ lat: -79.058407 lon: 35.106225 ][ lat: -78.944666 lon: 35.106225 ][ lat: -78.944666 lon: 35.177993 ][ lat: -79.058407 lon: 35.177993 ]]",geo4.getCoordinates().toString());
  }
  finally {
    is.close();
  }
}
 

Example 25

From project GoFleetLSServer, under directory /osrm-connector/src/main/java/org/emergya/osrm/.

Source file: OSRM.java

  19 
vote

private List<JAXBElement<?>> decodeRouteGeometry(List<JAXBElement<?>> list,CoordinateReferenceSystem targetCRS,CoordinateReferenceSystem sourceCRS,JsonParser jp) throws NoSuchAuthorityCodeException, FactoryException, MismatchedDimensionException, TransformException, JsonParseException, IOException {
  MathTransform transform=null;
  LOG.trace(targetCRS.toWKT());
  LOG.trace(sourceCRS.toWKT());
  jp.nextToken();
  while (jp.nextToken() == JsonToken.START_ARRAY && jp.getCurrentToken() != null) {
    jp.nextToken();
    Double lat=jp.getDoubleValue();
    jp.nextToken();
    Double lon=jp.getDoubleValue();
    jp.nextToken();
    Coordinate coord=new Coordinate(lat,lon);
    Point sourceGeometry=gf.createPoint(coord);
    LOG.trace(sourceGeometry);
    if (sourceCRS != targetCRS) {
      if (transform == null)       transform=CRS.findMathTransform(sourceCRS,targetCRS);
      sourceGeometry=JTS.transform(sourceGeometry,transform).getCentroid();
      LOG.trace(sourceGeometry);
    }
    DirectPositionListType e=new DirectPositionListType();
    e.getValue().add(sourceGeometry.getY());
    e.getValue().add(sourceGeometry.getX());
    JAXBElement<DirectPositionListType> elem=new JAXBElement<DirectPositionListType>(new QName("http://www.opengis.net/gml","pos","gml"),DirectPositionListType.class,e);
    list.add(elem);
  }
  return list;
}
 

Example 26

From project grouperfish, under directory /service/src/main/java/com/mozilla/grouperfish/base/json/.

Source file: JsonValidator.java

  19 
vote

public boolean isValid(String json) throws IOException {
  if (json.length() == 0) {
    return false;
  }
  try {
    JsonParser parser=jsonFactory.createJsonParser(json);
    while (parser.nextToken() != null) {
    }
  }
 catch (  JsonParseException e) {
    log.error("Error parsing JSON",e);
    return false;
  }
  return true;
}
 

Example 27

From project hcatalog, under directory /src/java/org/apache/hcatalog/data/.

Source file: JsonSerDe.java

  19 
vote

/** 
 * Takes JSON string in Text form, and has to return an object representation above it that's readable by the corresponding object inspector. For this implementation, since we're using the jackson parser, we can construct our own object implementation, and we use HCatRecord for it
 */
@Override public Object deserialize(Writable blob) throws SerDeException {
  Text t=(Text)blob;
  JsonParser p;
  List<Object> r=new ArrayList<Object>(Collections.nCopies(columnNames.size(),null));
  try {
    p=jsonFactory.createJsonParser(new ByteArrayInputStream((t.getBytes())));
    if (p.nextToken() != JsonToken.START_OBJECT) {
      throw new IOException("Start token not found where expected");
    }
    JsonToken token;
    while (((token=p.nextToken()) != JsonToken.END_OBJECT) && (token != null)) {
      populateRecord(r,token,p,schema);
    }
  }
 catch (  JsonParseException e) {
    LOG.warn("Error [{}] parsing json text [{}].",e,t);
    LOG.debug(null,e);
    throw new SerDeException(e);
  }
catch (  IOException e) {
    LOG.warn("Error [{}] parsing json text [{}].",e,t);
    LOG.debug(null,e);
    throw new SerDeException(e);
  }
  return new DefaultHCatRecord(r);
}
 

Example 28

From project jafka, under directory /src/main/java/com/sohu/jafka/consumer/.

Source file: TopicCount.java

  19 
vote

public static TopicCount parse(String consumerIdString,String jsonString){
  try {
    Map<String,Integer> topicCountMap=mapper.readValue(jsonString,new TypeReference<Map<String,Integer>>(){
    }
);
    return new TopicCount(consumerIdString,topicCountMap);
  }
 catch (  JsonParseException e) {
    throw new IllegalArgumentException("error parse consumer json string " + jsonString,e);
  }
catch (  JsonMappingException e) {
    throw new IllegalArgumentException("error parse consumer json string " + jsonString,e);
  }
catch (  IOException e) {
    throw new IllegalArgumentException("error parse consumer json string " + jsonString,e);
  }
}
 

Example 29

From project jHipChat, under directory /src/main/java/com/github/hipchat/api/messages/.

Source file: MessageParser.java

  19 
vote

public static List<HistoryMessage> parseRoomHistory(Room origin,InputStream input) throws JsonParseException, JsonMappingException, IOException {
  JsonParser jp=HipChat.JSON_FACTORY.createJsonParser(input);
  ObjectMapper mapper=new ObjectMapper();
  List<HistoryMessage> messages=null;
  jp.nextToken();
  while (jp.nextToken() != JsonToken.END_OBJECT) {
    String tag=jp.getText();
    if ("messages".equals(tag)) {
      jp.nextToken();
      while (jp.nextToken() != JsonToken.END_ARRAY) {
        HistoryMessage msg=parseHistoryMessage(origin,mapper,jp);
        if (messages == null) {
          messages=new ArrayList<HistoryMessage>();
        }
        messages.add(msg);
      }
    }
  }
  if (messages == null) {
    messages=Collections.emptyList();
  }
  return messages;
}
 

Example 30

From project lightbox-android-webservices, under directory /LightboxAndroidWebServices/src/com/lightbox/android/webservices/processors/.

Source file: JacksonProcessor.java

  19 
vote

public T parse(Class<T> parsedClass,InputStream source,boolean useNamingStrategy) throws ParsingException {
  T parsedObject=null;
  try {
    ObjectMapper objectMapper=useNamingStrategy ? sObjectMapper : sObjectMapperWithoutNamingStrategy;
    parsedObject=objectMapper.readValue(source,parsedClass);
  }
 catch (  JsonParseException e) {
    Log.w(TAG,e);
    throw new ParsingException(e);
  }
catch (  JsonMappingException e) {
    Log.w(TAG,e);
    throw new ParsingException(e);
  }
catch (  IOException e) {
    Log.w(TAG,e);
    throw new ParsingException(e);
  }
  return parsedObject;
}
 

Example 31

From project mongo-jackson-mapper, under directory /src/main/java/net/vz/mongodb/jackson/internal/stream/.

Source file: DBDecoderBsonParser.java

  19 
vote

@Override public Object getEmbeddedObject() throws IOException, JsonParseException {
  Object object=super.getEmbeddedObject();
  if (object instanceof ObjectId) {
    return ObjectIdConvertor.convert((ObjectId)object);
  }
 else {
    return object;
  }
}
 

Example 32

From project netty-socketio, under directory /src/main/java/com/corundumstudio/socketio/parser/.

Source file: JacksonJsonSupport.java

  19 
vote

private Object readObject(ObjectMapper mapper,JsonNode rootNode) throws IOException, JsonParseException, JsonMappingException {
  Class<?> clazz=Object.class;
  ObjectNode root=(ObjectNode)rootNode;
  JsonNode node=root.remove(configuration.getJsonTypeFieldName());
  if (node != null) {
    try {
      String typeName=node.asText();
      Class<?> supportClazz=Class.forName(typeName);
      if (classes.contains(supportClazz)) {
        clazz=supportClazz;
      }
    }
 catch (    ClassNotFoundException e) {
    }
  }
  Object val=mapper.readValue(root,clazz);
  return val;
}
 

Example 33

From project objectos-comuns-sitebricks, under directory /src/main/java/br/com/objectos/comuns/sitebricks/json/.

Source file: JsonsGuice.java

  19 
vote

@SuppressWarnings("unchecked") @Override public Map<String,Object> asMap(String json){
  try {
    return mapper.readValue(json,Map.class);
  }
 catch (  JsonParseException e) {
    throw Throwables.propagate(e);
  }
catch (  JsonMappingException e) {
    throw Throwables.propagate(e);
  }
catch (  IOException e) {
    throw Throwables.propagate(e);
  }
}
 

Example 34

From project onebusaway-nyc, under directory /onebusaway-nyc-admin-webapp/src/main/java/org/onebusaway/nyc/admin/service/impl/.

Source file: VehicleStatusServiceImpl.java

  19 
vote

private <T>T convertToObject(String content,Class<T> objectType){
  T object=null;
  try {
    object=mapper.readValue(content,objectType);
  }
 catch (  JsonParseException e) {
    log.error("Error parsing json content : " + e);
    e.printStackTrace();
  }
catch (  JsonMappingException e) {
    log.error("Error parsing json content : " + e);
    e.printStackTrace();
  }
catch (  IOException e) {
    log.error("Error parsing json content : " + e);
    e.printStackTrace();
  }
  return object;
}
 

Example 35

From project OpenConext-api, under directory /coin-api-war/src/test/java/nl/surfnet/coin/api/.

Source file: GroupProviderConfigurationTest.java

  19 
vote

private List<GroupProvider> getGroupProviders() throws JsonParseException, JsonMappingException, IOException {
  List<GroupProvider> groupProviders=objectMapper.readValue(new ClassPathResource(GROUP_PROVIDERS_CONFIGURATION_JSON).getInputStream(),new TypeReference<List<GroupProvider>>(){
  }
);
  return groupProviders;
}
 

Example 36

From project pangool, under directory /core/src/main/java/com/datasalt/pangool/tuplemr/.

Source file: TupleMRConfig.java

  19 
vote

private static TupleMRConfig parse(JsonParser parser) throws IOException {
  try {
    return parse(MAPPER.readTree(parser));
  }
 catch (  JsonParseException e) {
    throw new IOException(e);
  }
}
 

Example 37

From project reddit-is-fun, under directory /src/com/andrewshu/android/reddit/comments/.

Source file: DownloadCommentsTask.java

  19 
vote

private void parseCommentsJSON(InputStream in) throws IOException, JsonParseException {
  int insertedCommentIndex;
  String genericListingError="Not a comments listing";
  try {
    Listing[] listings=mObjectMapper.readValue(in,Listing[].class);
    Assert.assertEquals(Constants.JSON_LISTING,listings[0].getKind(),genericListingError);
    ListingData threadListingData=listings[0].getData();
    if (StringUtils.isEmpty(threadListingData.getModhash()))     mSettings.setModhash(null);
 else     mSettings.setModhash(threadListingData.getModhash());
    if (Constants.LOGGING)     Log.d(TAG,"Successfully got OP listing[0]: modhash " + mSettings.getModhash());
    ThingListing threadThingListing=threadListingData.getChildren()[0];
    Assert.assertEquals(Constants.THREAD_KIND,threadThingListing.getKind(),genericListingError);
    if (isInsertingEntireThread()) {
      parseOP(threadThingListing.getData());
      insertedCommentIndex=0;
      disableLoadingScreenKeepProgress();
    }
 else {
      insertedCommentIndex=mPositionOffset - 1;
    }
    ListingData commentListingData=listings[1].getData();
    for (    ThingListing commentThingListing : commentListingData.getChildren()) {
      insertedCommentIndex=insertNestedComment(commentThingListing,0,insertedCommentIndex + 1);
    }
    mProcessCommentsTask.mergeLowPriorityListToMainList();
  }
 catch (  Exception ex) {
    if (Constants.LOGGING)     Log.e(TAG,"parseCommentsJSON",ex);
  }
}
 

Example 38

From project SchoolPlanner4Untis, under directory /src/edu/htl3r/schoolplanner/backend/network/json/.

Source file: JSONNetwork.java

  19 
vote

private <E>DataFacade<List<E>> getList(E typeDef,JSONRequestMethod method,JSONObject params){
  DataFacade<List<E>> data=new DataFacade<List<E>>();
  try {
    DataFacade<JSONObject> jsonData=requestJSONData(method,params);
    if (jsonData.isSuccessful()) {
      ObjectMapper objectMapper=new ObjectMapper();
      List<E> list=objectMapper.readValue(jsonData.getData().getJSONArray(JSONResponseObjectKeys.RESULT).toString(),objectMapper.getTypeFactory().constructCollectionType(List.class,typeDef.getClass()));
      data.setData(list);
    }
 else {
      data.setErrorMessage(jsonData.getErrorMessage());
    }
  }
 catch (  JSONException e) {
    data.setErrorMessage(getErrorMessage(e));
  }
catch (  JsonParseException e) {
    data.setErrorMessage(getErrorMessage(e));
  }
catch (  JsonMappingException e) {
    data.setErrorMessage(getErrorMessage(e));
  }
catch (  IOException e) {
    data.setErrorMessage(getErrorMessage(e));
  }
  return data;
}
 

Example 39

From project seam-social, under directory /impl/src/main/java/org/jboss/seam/social/oauth/.

Source file: JsonMapper.java

  19 
vote

public <T>T readValue(HttpResponse resp,Class<T> clazz){
  T res=null;
  try {
    res=delegate.readValue(resp.getStream(),clazz);
  }
 catch (  JsonParseException e) {
    e.printStackTrace();
  }
catch (  JsonMappingException e) {
    e.printStackTrace();
  }
catch (  IOException e) {
    e.printStackTrace();
  }
  return res;
}
 

Example 40

From project serengeti-ws, under directory /cli/src/main/java/com/vmware/bdd/cli/commands/.

Source file: CommandsUtils.java

  19 
vote

public static <T>T getObjectByJsonString(Class<T> entityType,String jsonString) throws JsonParseException, JsonMappingException, IOException {
  ObjectMapper mapper=getMapper();
  T NodeGroupsCreate=null;
  NodeGroupsCreate=mapper.readValue(jsonString,entityType);
  return NodeGroupsCreate;
}
 

Example 41

From project sitebricks, under directory /sitebricks-client/src/main/java/com/google/sitebricks/client/transport/.

Source file: JacksonJsonTransportWithConverters.java

  19 
vote

private Object getSourceObject(JsonParser jp,DeserializationContext ctxt) throws JsonParseException, IOException {
  JsonToken t=jp.getCurrentToken();
  if (t == JsonToken.VALUE_NUMBER_INT) {
    return jp.getLongValue();
  }
 else   if (t == JsonToken.VALUE_NUMBER_FLOAT) {
    return jp.getDoubleValue();
  }
 else   if (t == JsonToken.VALUE_TRUE) {
    return Boolean.TRUE;
  }
 else   if (t == JsonToken.VALUE_FALSE) {
    return Boolean.FALSE;
  }
 else   if (t == JsonToken.VALUE_STRING) {
    return jp.getText();
  }
 else   throw new IllegalStateException();
}
 

Example 42

From project spring-batch-admin, under directory /spring-batch-admin-manager/src/test/java/org/springframework/batch/admin/web/.

Source file: JsonWrapper.java

  19 
vote

@SuppressWarnings("unchecked") public JsonWrapper(String content) throws Exception {
  this.content=content;
  try {
    target=new MappingJsonFactory().createJsonParser(content.replace("\\","/")).readValueAs(Map.class);
  }
 catch (  JsonParseException e) {
    throw new JsonMappingException("Cannot create wrapper for:\n" + content,e);
  }
  context=new StandardEvaluationContext();
  context.addPropertyAccessor(new MapAccessor());
  parser=new SpelExpressionParser();
}
 

Example 43

From project spring-data-document-examples, under directory /couchdb-myrestaurants/src/main/java/com/springone/myrestaurants/web/.

Source file: CouchDbMappingJacksonHttpMessageConverter.java

  19 
vote

private Object success(Class<?> clazz,HttpInputMessage inputMessage) throws JsonParseException, IOException {
  JsonParser jp=objectMapper.getJsonFactory().createJsonParser(inputMessage.getBody());
  if (jp.nextToken() != JsonToken.START_OBJECT) {
    throw new RuntimeException("Expected data to start with an Object");
  }
  Map<String,Integer> fields=readHeaderFields(jp);
  List result;
  if (fields.containsKey(TOTAL_ROWS_FIELD_NAME)) {
    int totalRows=fields.get(TOTAL_ROWS_FIELD_NAME);
    if (totalRows == 0) {
      return Collections.emptyList();
    }
    result=new ArrayList(totalRows);
  }
 else {
    result=new ArrayList();
  }
  ParseState state=new ParseState();
  Object first=parseFirstRow(jp,state,clazz);
  if (first == null) {
    return Collections.emptyList();
  }
 else {
    result.add(first);
  }
  while (jp.getCurrentToken() != null) {
    skipToField(jp,state.docFieldName,state);
    if (atEndOfRows(jp)) {
      return result;
    }
    result.add(jp.readValueAs(clazz));
    endRow(jp,state);
  }
  return result;
}
 

Example 44

From project spring-flex, under directory /spring-flex-core/src/main/java/org/springframework/flex/config/json/.

Source file: JsonConfigMapParser.java

  19 
vote

ConfigMap parseJsonConfigMap(String text) throws JsonParseException, IOException {
  JsonParser parser=FACTORY.createJsonParser(text);
  Assert.isTrue(parser.nextToken() == JsonToken.START_OBJECT,"Text does not appear to be a proper JSON string.");
  ConfigMap configMap=parseJsonObject(parser);
  parser.close();
  return configMap;
}
 

Example 45

From project spring-social-facebook, under directory /spring-social-facebook/src/main/java/org/springframework/social/facebook/api/impl/.

Source file: FacebookErrorHandler.java

  19 
vote

@SuppressWarnings("unchecked") private Map<String,String> extractErrorDetailsFromResponse(ClientHttpResponse response) throws IOException {
  ObjectMapper mapper=new ObjectMapper(new JsonFactory());
  String json=readFully(response.getBody());
  if (json.equals("false")) {
    throw new InsufficientPermissionException();
  }
  try {
    Map<String,Object> responseMap=mapper.<Map<String,Object>>readValue(json,new TypeReference<Map<String,Object>>(){
    }
);
    if (responseMap.containsKey("error")) {
      return (Map<String,String>)responseMap.get("error");
    }
  }
 catch (  JsonParseException e) {
    return null;
  }
  return null;
}
 

Example 46

From project spring-social-flickr, under directory /core/src/main/java/org/springframework/social/flickr/api/impl/.

Source file: FlickrObjectMapper.java

  19 
vote

protected Object _unwrapAndDeserialize(JsonParser jp,JavaType rootType,DeserializationContext ctxt,JsonDeserializer<Object> deser) throws IOException, JsonParseException, JsonMappingException {
  ObjectMapper mapper=new ObjectMapper();
  mapper.setDeserializationConfig(ctxt.getConfig());
  mapper.disable(DeserializationConfig.Feature.UNWRAP_ROOT_VALUE);
  jp.setCodec(mapper);
  JsonNode tree=jp.readValueAsTree();
  JsonNode statNode=tree.get("stat");
  String status=statNode.getTextValue();
  if (!"ok".equals(status)) {
    JsonNode msgNode=tree.get("message");
    String errorMsg=msgNode.getTextValue();
    JsonNode codeNode=tree.get("code");
    String errorCode=codeNode.getTextValue();
    throw new FlickrException(errorMsg);
  }
  jp=jp.getCodec().treeAsTokens(tree);
  jp.nextToken();
  SerializedString rootName=_deserializerProvider.findExpectedRootName(ctxt.getConfig(),rootType);
  if (jp.getCurrentToken() != JsonToken.START_OBJECT) {
    throw JsonMappingException.from(jp,"Current token not START_OBJECT (needed to unwrap root name '" + rootName + "'), but "+ jp.getCurrentToken());
  }
  if (jp.nextToken() != JsonToken.FIELD_NAME) {
    throw JsonMappingException.from(jp,"Current token not FIELD_NAME (to contain expected root name '" + rootName + "'), but "+ jp.getCurrentToken());
  }
  String actualName=jp.getCurrentName();
  if ("stat".equals(actualName)) {
    return null;
  }
  jp.nextToken();
  Object result=deser.deserialize(jp,ctxt);
  jp.nextToken();
  jp.nextToken();
  if (jp.nextToken() != JsonToken.END_OBJECT) {
    throw JsonMappingException.from(jp,"Current token not END_OBJECT (to match wrapper object with root name '" + rootName + "'), but "+ jp.getCurrentToken());
  }
  return result;
}
 

Example 47

From project spring-social-mixcloud, under directory /src/main/java/org/springframework/social/mixcloud/api/impl/.

Source file: MixcloudErrorHandler.java

  19 
vote

@SuppressWarnings("rawtypes") private SocialException extractExceptionFromResponse(ClientHttpResponse response) throws IOException {
  ObjectMapper mapper=new ObjectMapper(new JsonFactory());
  try {
    String json=readFully(response.getBody());
    Map<String,String> responseMap=mapper.<Map<String,String>>readValue(json,new TypeReference<Map<String,Object>>(){
    }
);
    if (responseMap.containsKey("error")) {
      Object error=responseMap.get("error");
      if (error instanceof String) {
        return new UncategorizedApiException(responseMap.get("error"),new RuntimeException(responseMap.get("error")));
      }
 else       if (error instanceof Map) {
        Map errorMap=(Map)error;
        String type=(String)((Map)error).get("type");
        if ("OAuthException".equals(type)) {
          return new InvalidAuthorizationException((String)errorMap.get("message"));
        }
        if ("ResourceNotFoundException".equals(type)) {
          return new ResourceNotFoundException((String)errorMap.get("message"));
        }
        return new UncategorizedApiException(responseMap.get("error"),new RuntimeException(responseMap.get("error")));
      }
 else {
        return null;
      }
    }
 else {
      return null;
    }
  }
 catch (  JsonParseException e) {
    return null;
  }
}
 

Example 48

From project spring-social-twitter, under directory /spring-social-twitter/src/main/java/org/springframework/social/twitter/api/impl/.

Source file: TwitterErrorHandler.java

  19 
vote

private Map<String,Object> extractErrorDetailsFromResponse(ClientHttpResponse response) throws IOException {
  ObjectMapper mapper=new ObjectMapper(new JsonFactory());
  try {
    return mapper.<Map<String,Object>>readValue(response.getBody(),new TypeReference<Map<String,Object>>(){
    }
);
  }
 catch (  JsonParseException e) {
    return null;
  }
}
 

Example 49

From project spring-social-yammer, under directory /spring-social-yammer/src/main/java/org/springframework/social/yammer/api/impl/.

Source file: YammerErrorHandler.java

  19 
vote

/** 
 * Error details are returned in the message body as JSON. Extract these in a map
 * @param response from yammer
 * @return json body as a map
 * @throws IOException if ItemStream is closed
 */
private Map<String,Object> extractErrorDetailsFromResponse(ClientHttpResponse response) throws IOException {
  ObjectMapper mapper=new ObjectMapper(new JsonFactory());
  try {
    return mapper.<Map<String,Object>>readValue(response.getBody(),new TypeReference<Map<String,Object>>(){
    }
);
  }
 catch (  JsonParseException e) {
    return null;
  }
}
 

Example 50

From project st-js, under directory /server/src/test/java/org/stjs/server/.

Source file: JacksonTest.java

  19 
vote

@Test public void testDeserializeArray() throws JsonParseException, JsonMappingException, IOException {
  ObjectMapper mapper=new ObjectMapper();
  mapper.registerModule(STJSModule.getModule());
  Array<Integer> a=mapper.readValue("[1,2,3]",mapper.getTypeFactory().constructCollectionLikeType(Array.class,Integer.class));
  assertNotNull(a);
  assertEquals(3,a.$length());
  assertEquals(2,(int)a.$get(1));
}
 

Example 51

From project tap, under directory /src/main/java/tap/core/.

Source file: MapperBridge.java

  19 
vote

/** 
 * @param wrapper
 * @param value
 * @param reporter
 * @throws IOException
 */
private void invokeMapper(KEY wrapper,VALUE value,Reporter reporter) throws IOException {
  if (isTextInput) {
    map((IN)value);
  }
 else   if (isStringInput) {
    map((IN)((Text)value).toString());
  }
 else   if (isProtoInput) {
    map((IN)((ProtobufWritable)value).get());
  }
 else   if (isJsonInput) {
    String json=((Text)value).toString();
    if (shouldSkip(json))     return;
    try {
      GenericContainer c=JsonToGenericRecord.jsonToRecord(json,inSchema);
      GenericDatumWriter<GenericContainer> writer=new GenericDatumWriter<GenericContainer>(inSchema);
      ByteArrayOutputStream bos=new ByteArrayOutputStream();
      writer.setSchema(inSchema);
      encoder=factory.binaryEncoder(bos,encoder);
      writer.write(c,encoder);
      byte[] data=bos.toByteArray();
      GenericDatumReader<IN> reader=new SpecificDatumReader<IN>(inSchema);
      reader.setSchema(inSchema);
      IN converted=reader.read(null,DecoderFactory.defaultFactory().createBinaryDecoder(data,null));
      map(converted);
    }
 catch (    JsonParseException jpe) {
      System.err.println("Failed to parse " + json + ": "+ jpe.getMessage());
      reporter.incrCounter("ColHadoopMapper","json-parse-error",1L);
      if (++parseErrors > maxAllowedErrors) {
        throw new RuntimeException(jpe);
      }
    }
  }
 else {
    map(((AvroWrapper<IN>)wrapper).datum());
  }
}
 

Example 52

From project TiVo-Commander, under directory /src/com/arantius/tivocommander/.

Source file: Utils.java

  19 
vote

public final static JsonNode parseJson(String json){
  try {
    return mMapper.readValue(json,JsonNode.class);
  }
 catch (  JsonMappingException e) {
    Log.e(LOG_TAG,"parseJson failure",e);
  }
catch (  JsonParseException e) {
    Log.e(LOG_TAG,"parseJson failure",e);
  }
catch (  IOException e) {
    Log.e(LOG_TAG,"parseJson failure",e);
  }
  logError("When parsing:\n" + json);
  return null;
}
 

Example 53

From project tourenplaner-server, under directory /src/de/tourenplaner/server/.

Source file: PrivateHandler.java

  19 
vote

/** 
 * Extracts and parses the JSON encoded content of the given HttpRequest, in case of error sends a EBADJSON answer to the client and returns null, the connection will be closed afterwards.
 * @param request HttpRequest
 * @return Returns parsed json map or null in case of an error
 * @throws IOException          Thrown if error message sending or reading json content fails
 * @throws JsonMappingException Thrown if mapping json content fails
 */
private Map<String,Object> getJSONContent(final HttpRequest request) throws IOException {
  Map<String,Object> objmap=null;
  final ChannelBuffer content=request.getContent();
  if (content.readableBytes() > 0) {
    try {
      objmap=mapper.readValue(new ChannelBufferInputStream(content),new TypeReference<Map<String,Object>>(){
      }
);
    }
 catch (    JsonParseException e) {
      responder.writeErrorMessage(ErrorMessage.EBADJSON,e.getMessage());
      objmap=null;
    }
  }
 else {
    responder.writeErrorMessage(ErrorMessage.EBADJSON_NOCONTENT);
  }
  return objmap;
}
 

Example 54

From project ubuntu-packaging-floodlight, under directory /src/main/java/net/floodlightcontroller/staticflowentry/.

Source file: StaticFlowEntries.java

  19 
vote

/** 
 * Gets the entry name of a flow mod
 * @param fmJson The OFFlowMod in a JSON representation
 * @return The name of the OFFlowMod, null if not found
 * @throws IOException If there was an error parsing the JSON
 */
public static String getEntryNameFromJson(String fmJson) throws IOException {
  MappingJsonFactory f=new MappingJsonFactory();
  JsonParser jp;
  try {
    jp=f.createJsonParser(fmJson);
  }
 catch (  JsonParseException e) {
    throw new IOException(e);
  }
  jp.nextToken();
  if (jp.getCurrentToken() != JsonToken.START_OBJECT) {
    throw new IOException("Expected START_OBJECT");
  }
  while (jp.nextToken() != JsonToken.END_OBJECT) {
    if (jp.getCurrentToken() != JsonToken.FIELD_NAME) {
      throw new IOException("Expected FIELD_NAME");
    }
    String n=jp.getCurrentName();
    jp.nextToken();
    if (jp.getText().equals(""))     continue;
    if (n == "name")     return jp.getText();
  }
  return null;
}
 

Example 55

From project usergrid-stack, under directory /core/src/main/java/org/usergrid/utils/.

Source file: JsonUtils.java

  19 
vote

public static Object parse(String json){
  try {
    return mapper.readValue(json,Object.class);
  }
 catch (  JsonParseException e) {
  }
catch (  JsonMappingException e) {
  }
catch (  IOException e) {
  }
  return null;
}
 

Example 56

From project vcap-java-client, under directory /cloudfoundry-client-lib/src/main/java/org/cloudfoundry/client/lib/rest/.

Source file: AbstractCloudControllerClient.java

  19 
vote

@Override public void handleError(ClientHttpResponse response) throws IOException {
  HttpStatus statusCode=response.getStatusCode();
switch (statusCode.series()) {
case CLIENT_ERROR:
    CloudFoundryException exception=new CloudFoundryException(statusCode,response.getStatusText());
  ObjectMapper mapper=new ObjectMapper();
if (response.getBody() != null) {
  try {
    @SuppressWarnings("unchecked") Map<String,Object> map=mapper.readValue(response.getBody(),Map.class);
    exception.setDescription(CloudUtil.parse(String.class,map.get("description")));
  }
 catch (  JsonParseException e) {
    exception.setDescription("Client error");
  }
}
 else {
  exception.setDescription("Client error");
}
throw exception;
case SERVER_ERROR:
throw new HttpServerErrorException(statusCode,response.getStatusText());
default :
throw new RestClientException("Unknown status code [" + statusCode + "]");
}
}
 

Example 57

From project wrml-prototype, under directory /src/main/java/org/wrml/core/io/.

Source file: JsonParserModelGraphReader.java

  19 
vote

public String next(){
  try {
    JsonToken token=getCurrentToken();
    while (token != null) {
      final String currentName=getCurrentName();
      token=getNextToken();
      if (token == JsonToken.END_OBJECT) {
        return null;
      }
      if ((currentName != null) && !currentName.equals(_CurrentName)) {
        _CurrentName=currentName;
        return currentName;
      }
    }
  }
 catch (  final JsonParseException e) {
    e.printStackTrace();
  }
catch (  final IOException e) {
    e.printStackTrace();
  }
  return null;
}
 

Example 58

From project zanata, under directory /zanata-war/src/test/java/org/zanata/rest/compat/v1_3/.

Source file: ProjectRawCompatibilityTest.java

  19 
vote

private List<Project> jsonParse(EnhancedMockHttpServletResponse response){
  ObjectMapper mapper=new ObjectMapper();
  try {
    return mapper.readValue(response.getContentAsString(),new TypeReference<List<Project>>(){
    }
);
  }
 catch (  JsonParseException e) {
    throw new AssertionError(e);
  }
catch (  JsonMappingException e) {
    throw new AssertionError(e);
  }
catch (  IllegalStateException e) {
    throw new AssertionError(e);
  }
catch (  IOException e) {
    throw new AssertionError(e);
  }
}