Example usage for com.fasterxml.jackson.databind ObjectMapper readValue

List of usage examples for com.fasterxml.jackson.databind ObjectMapper readValue

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind ObjectMapper readValue.

Prototype

@SuppressWarnings("unchecked")
    public <T> T readValue(byte[] src, JavaType valueType)
            throws IOException, JsonParseException, JsonMappingException 

Source Link

Usage

From source file:carmen.types.Location.java

public static Location parseLocation(String jsonString)
        throws JsonParseException, JsonMappingException, IOException {
    ObjectMapper mapper = new ObjectMapper();
    @SuppressWarnings("unchecked")
    Map<String, Object> locationMap = (Map<String, Object>) mapper.readValue(jsonString, Map.class);

    return parseLocationFromJsonObj(locationMap);
}

From source file:com.ubershy.streamsis.project.ProjectSerializator.java

/**
 * Deserialize(load) {@link CuteProject} from file.
 *
 * @param path/*from   w ww  .j a  v  a 2s  .  c  o m*/
 *            the path of the file to deserialize
 * @return {@link CuteProject}
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public static CuteProject deSerializeFromFile(String path) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);
    mapper.configure(DeserializationFeature.ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT, true);
    CuteProject project = null;
    try {
        project = mapper.readValue(Files.readAllBytes(Paths.get(path)), CuteProject.class);
    } catch (JsonGenerationException e) {
        logger.error("CuteProject opening fail: JsonGeneration error");
        e.printStackTrace();
        throw e;
    } catch (JsonMappingException e) {
        logger.error(
                "CuteProject opening fail: mapping error. Can't deserialize Project file. It has different or outdated format "
                        + path);
        e.printStackTrace();
        throw e;
    } catch (IOException e) {
        logger.error("CuteProject opening fail: IO error " + path);
        throw e;
    }
    logger.info("CuteProject opening success");
    return project;
}

From source file:HttpGETCollectionExample.java

private static void httpGETCollectionExample() throws IOException {
    //        String testJson="{\"name\":\"mkyong\",\"age\":33,\"position\":\"Developer\",\"salary\":7500,\"skills\":[\"java\",\"python\"]}";
    //        ObjectMapper map = new ObjectMapper();
    //        Staff staff1 = map.readValue(testJson, Staff.class);
    //        // ww w  .j  a v  a2s  .  com
    //        String testApi="{\"program\":\"CRS610MI\",\"transaction\":\"LstByName\"}";
    //        ObjectMapper map1 = new ObjectMapper();
    //        Staff r=map1.readValue(testApi, Staff.class);

    ClientConfig clientConfig = new ClientConfig();

    HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic("JCHAUT", "Sgknoa1984");
    clientConfig.register(feature);

    clientConfig.register(JacksonFeature.class);

    String urlExecute = "http://192.168.111.17:20007/m3api-rest/execute/";
    String urlMetadata = "http://192.168.111.17:20007/m3api-rest/metadata/";
    String pgmAPI = "PMS070MI";
    String trnAPI = "RptOperation";

    Client client = ClientBuilder.newClient(clientConfig);
    WebTarget webTarget = client.target(urlExecute + pgmAPI + "/" + trnAPI);
    //        WebTarget webTarget = client.target(urlMetadata + pgmAPI);

    Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
    Response response = invocationBuilder.get();

    System.out.println(response.getStatus());
    System.out.println(response.getStatusInfo());
    ObjectMapper mapper = new ObjectMapper();
    if (response.getStatus() == 200) {
        String responseAsString = response.readEntity(String.class);
        System.out.println(responseAsString);
        //MIProgramMetadata pgmmeta=mapper.readValue(XMLtoJSonConverter.getJSONFromXML(responseAsString).toString(), MIProgramMetadata.class);
        try {
            MIResult res = mapper.readValue(responseAsString, MIResult.class);
        } catch (Exception e) {
            MIError err = mapper.readValue(responseAsString, MIError.class);
        }
    }
}

From source file:com.tjtolley.roborally.game.BoardDefinition.java

public static BoardDefinition fromSavedBoard(String boardName) {
    try {/*from   w  w  w.ja va 2s  .co  m*/
        ObjectMapper mapper = new ObjectMapper();
        File file = new File("src/main/resources/assets/boards/" + boardName.toLowerCase() + ".json");
        if (!file.exists()) {
            throw new IllegalArgumentException("File not found");
        }
        Map readValue = mapper.readValue(file, Map.class);
        int width = (int) readValue.get("width");
        int height = (int) readValue.get("height");
        List<List<Map<String, Object>>> tiles = (List<List<Map<String, Object>>>) readValue.get("board");
        List<List<Tile>> board = Lists.newArrayList();
        for (int row = 0; row < width; row++) {
            board.add(row, Lists.<Tile>newArrayList());
        }
        for (List<Map<String, Object>> list : tiles) {
            for (Map<String, Object> tileMap : list) {
                final int x = (int) tileMap.get("x");
                List<Tile> column = board.get(x);
                final int y = (int) tileMap.get("y");
                final Direction direction = tileMap.containsKey("rotation")
                        ? Direction.valueOf((String) tileMap.get("rotation"))
                        : Direction.NORTH;
                final Tile.EdgeType northEdge = tileMap.containsKey("northEdge")
                        ? EdgeType.valueOf((String) tileMap.get("northEdge"))
                        : Tile.EdgeType.EMPTY;
                final Tile.EdgeType southEdge = tileMap.containsKey("southEdge")
                        ? EdgeType.valueOf((String) tileMap.get("southEdge"))
                        : Tile.EdgeType.EMPTY;
                final Tile.EdgeType eastEdge = tileMap.containsKey("eastEdge")
                        ? EdgeType.valueOf((String) tileMap.get("eastEdge"))
                        : Tile.EdgeType.EMPTY;
                final Tile.EdgeType westEdge = tileMap.containsKey("westEdge")
                        ? EdgeType.valueOf((String) tileMap.get("westEdge"))
                        : Tile.EdgeType.EMPTY;
                column.add(y, new Tile(Tile.TileType.valueOf((String) tileMap.get("tileType")), x, y, direction,
                        northEdge, southEdge, eastEdge, westEdge));
            }
        }
        return new BoardDefinition((String) readValue.get("name"), board, width, height);
    } catch (IOException ex) {
        throw new IllegalStateException("Unable to parse board", ex);
    }
}

From source file:com.maxmind.geoip2.WebServiceClient.java

private static void handle4xxStatus(String body, int status, GenericUrl uri)
        throws GeoIp2Exception, HttpException {

    if (body == null) {
        throw new HttpException("Received a " + status + " error for " + uri + " with no body", status,
                uri.toURL());//from   www  .j  a  v a 2s. c o  m
    }

    try {
        ObjectMapper mapper = new ObjectMapper();
        Map<String, String> content = mapper.readValue(body, new TypeReference<HashMap<String, String>>() {
        });
        handleErrorWithJsonBody(content, body, status, uri);
    } catch (HttpException e) {
        throw e;
    } catch (IOException e) {
        throw new HttpException("Received a " + status + " error for " + uri
                + " but it did not include the expected JSON body: " + body, status, uri.toURL());
    }
}

From source file:com.netsteadfast.greenstep.sys.CxfServerBean.java

@SuppressWarnings("unchecked")
public static Map<String, Object> shutdownOrReloadCallOneSystem(HttpServletRequest request, String system,
        String type) throws ServiceException, Exception {
    if (StringUtils.isBlank(system) || StringUtils.isBlank(type)) {
        throw new ServiceException(SysMessageUtil.get(GreenStepSysMsgConstants.PARAMS_BLANK));
    }//from ww  w.  j a v a2s  .  co m
    String urlStr = ApplicationSiteUtils.getBasePath(system, request) + "config-services?type=" + type
            + "&value=" + createParamValue();
    logger.info("shutdownOrReloadCallSystem , url=" + urlStr);
    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(urlStr);
    client.executeMethod(method);
    byte[] responseBody = method.getResponseBody();
    if (null == responseBody) {
        throw new Exception("no response!");
    }
    String content = new String(responseBody, Constants.BASE_ENCODING);
    logger.info("shutdownOrReloadCallSystem , system=" + system + " , type=" + type + " , response=" + content);
    ObjectMapper mapper = new ObjectMapper();
    Map<String, Object> dataMap = null;
    try {
        dataMap = (Map<String, Object>) mapper.readValue(content, HashMap.class);
    } catch (JsonParseException e) {
        logger.error(e.getMessage().toString());
    } catch (JsonMappingException e) {
        logger.error(e.getMessage().toString());
    }
    if (null == dataMap) {
        throw new Exception("response content error!");
    }
    return dataMap;
}

From source file:loadTest.loadTestLib.LUtil.java

public static List<LoadTestConfigModel> readJSONConfig() throws IOException {
    InputStream in = LUtil.class.getClassLoader().getResourceAsStream("loadTestConfig.json");
    ObjectMapper mapper = new ObjectMapper();
    List<LoadTestConfigModel> myObjects = mapper.readValue(in,
            mapper.getTypeFactory().constructCollectionType(List.class, LoadTestConfigModel.class));
    return myObjects;
}

From source file:controllers.skilltag.SkillTagApp.java

private static List<ExpertListVO> getTagExperts(String p, Long i, String s, String cf, String ssf, String ef,
        String gf, String o, String ot) {
    List<ExpertListVO> elv = new ArrayList<ExpertListVO>();
    List<Expert> experts = Expert.getPartExpert(p, 18, i, s, cf, ssf, ef, gf, o, ot);
    for (Expert e : experts) {
        ExpertListVO ev = new ExpertListVO();
        ev.setId(e.id);//from   w w  w . j  av a2  s.  c o  m
        ev.setCountry(e.country);
        ev.setHeadUrl(e.headUrl);
        ev.setUserId(e.userId);
        ev.setUserName(e.userName);
        List<STagVo> stvs = new ArrayList<STagVo>();
        ObjectMapper objectMapper = JackJsonUtil.getMapperInstance();
        List<String> list = null;
        try {
            if (StringUtils.isNotBlank(e.skillsTags)) {
                list = objectMapper.readValue(e.skillsTags, List.class);
            }
        } catch (Exception e1) {
            // e1.printStackTrace();
        }
        if (list != null)
            for (String tagName : list) {
                STagVo sTagVo = new STagVo();
                sTagVo.setTag(tagName);
                stvs.add(sTagVo);
            }
        ev.setJob(e.job);
        ev.setSkillsTags(stvs);
        ev.setCommentNum(e.commentNum);
        ev.setPayType(e.payType);
        ev.setAverageScore(e.averageScore);
        ev.setCountryUrl(Constants.countryPicKV.get(e.country));
        elv.add(ev);
    }
    //      if(Logger.isDebugEnabled()){
    //         System.out.println("query data  --->>>>>");
    //         
    //         for(ExpertListVO vo:elv){
    //            System.out.print(vo.getUserName());
    //            System.out.print(",");
    //         }
    //         System.out.println();
    //      }

    return elv;
}

From source file:io.orchestrate.client.ResponseConverterUtil.java

@SuppressWarnings("unchecked")
@Deprecated/* www  .j  ava2  s .c o  m*/
public static <T> T jsonToDomainObject(ObjectMapper mapper, String rawValue, Class<T> clazz)
        throws IOException {
    if (clazz == null || clazz == Void.class || rawValue == null || rawValue.isEmpty()) {
        return null;
    }

    if (clazz.equals(String.class)) {
        return (T) rawValue;
    }
    return mapper.readValue(rawValue, clazz);
}

From source file:com.marklogic.client.functionaltest.TestPOJOQueryBuilderGeoQueries.java

public static void createAutomaticGeoIndex() throws Exception {
    boolean succeeded = false;
    File jsonFile = null;/*from  ww  w  .  j  a  v  a2s. c o  m*/
    try {
        GenerateIndexConfig.main(new String[] { "-classes", "com.marklogic.client.functionaltest.GeoCompany",
                "-file", "TestAutomatedGeoPathRangeIndex.json" });

        jsonFile = new File("TestAutomatedGeoPathRangeIndex.json");
        ObjectMapper mapper = new ObjectMapper();
        JsonNode jnode = mapper.readValue(jsonFile, JsonNode.class);

        if (!jnode.isNull()) {
            setPathRangeIndexInDatabase(dbName, jnode);
            succeeded = true;
        } else {
            assertTrue("testArtifactIndexedOnString - No Json node available to insert into database",
                    succeeded);
        }

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            jsonFile.delete();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}