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:com.raythos.sentilexo.persistence.cql.PersistedEntity.java

public static PersistedEntity fromBinaryJSon(byte[] data, Class classType) {
    try {//from  ww w.j a  v  a  2s  .c o  m
        SmileFactory f = new SmileFactory();
        f.configure(SmileParser.Feature.REQUIRE_HEADER, true);

        ObjectMapper mapper = new ObjectMapper(f);

        mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
        Object result = mapper.readValue(data, classType);
        return (PersistedEntity) result;
    } catch (IOException ex) {
        Logger.getLogger(PersistedEntity.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    }
}

From source file:com.damnhandy.uri.template.conformance.AbstractUriTemplateConformanceTest.java

/**
 * <p>/*from   w  w w.j  av  a2 s  .  c o m*/
 * Loads the test data from the JSON file and generated the parameter list.
 * </p>
 *
 * @param file
 * @return
 * @throws Exception
 */
@SuppressWarnings("unchecked")
protected static Collection<Object[]> loadTestData(File file) throws Exception {
    InputStream in = new FileInputStream(file);
    try {
        ObjectMapper mapper = new ObjectMapper();
        Map<String, Object> testsuites = mapper.readValue(in, new TypeReference<Map<String, Object>>() {
        });

        List<Object[]> params = new ArrayList<Object[]>();
        for (Map.Entry<String, Object> entry : testsuites.entrySet()) {
            String name = entry.getKey();
            Map<String, Object> testsuite = (Map<String, Object>) entry.getValue();
            Map<String, Object> variables = (Map<String, Object>) testsuite.get("variables");
            List<List<Object>> testcases = (List<List<Object>>) testsuite.get("testcases");

            for (List<Object> test : testcases) {
                Object[] p = new Object[4];
                p[0] = variables;
                p[1] = test.get(0); // expression
                p[2] = test.get(1); // expected result
                p[3] = name; // test suite label
                params.add(p);
            }
        }
        return params;
    } finally {
        in.close();
    }

}

From source file:com.yahoo.sshd.tools.artifactory.ArtifactMetaData.java

public static ArtifactMetaData decode(String json) throws ArtifactMetaDataParseFailureException {
    ObjectMapper mapper = new ObjectMapper();
    try {//from   ww  w.ja v  a  2 s. co m
        return mapper.readValue(json, ArtifactMetaData.class);
    } catch (IOException e) {
        throw new ArtifactMetaDataParseFailureException("parsing " + json + " failed", e);
    }
}

From source file:com.yahoo.sshd.tools.artifactory.ArtifactMetaData.java

public static ArtifactMetaData decode(InputStream json) throws ArtifactMetaDataParseFailureException {
    ObjectMapper mapper = new ObjectMapper();
    try {//from  w  ww.  j ava2 s.c om
        return mapper.readValue(json, ArtifactMetaData.class);
    } catch (IOException e) {
        throw new ArtifactMetaDataParseFailureException("parsing " + json + " failed", e);
    }
}

From source file:org.apache.streams.converter.TypeConverterUtil.java

public static Object convert(Object object, Class outClass, ObjectMapper mapper) {
    ObjectNode node = null;/*from   w  ww  .  j  av  a  2 s  .c  o m*/
    Object outDoc = null;
    if (object instanceof String) {
        try {
            node = mapper.readValue((String) object, ObjectNode.class);
        } catch (IOException e) {
            LOGGER.warn(e.getMessage());
            LOGGER.warn(object.toString());
        }
    } else {
        node = mapper.convertValue(object, ObjectNode.class);
    }

    if (node != null) {
        try {
            if (outClass == String.class)
                outDoc = mapper.writeValueAsString(node);
            else
                outDoc = mapper.convertValue(node, outClass);

        } catch (Throwable e) {
            LOGGER.warn(e.getMessage());
            LOGGER.warn(node.toString());
        }
    }

    return outDoc;
}

From source file:edu.sjsu.cohort6.esp.common.CommonUtils.java

/**
 * Converts a JSON array of objects to List of Java Object types.
 * For example, convert a JSON array of students to List<Student>.
 *
 * @param jsonArrayStr/*w ww.ja  va2 s  . c o  m*/
 * @param clazz
 * @param <T>
 * @return
 * @throws java.io.IOException
 */
public static <T> List<T> convertJsonArrayToList(String jsonArrayStr, Class<T> clazz)
        throws java.io.IOException {
    ObjectMapper mapper = new ObjectMapper();
    //jsonArrayStr = removeIdField(jsonArrayStr);
    return mapper.readValue(jsonArrayStr,
            TypeFactory.defaultInstance().constructCollectionType(List.class, clazz));
}

From source file:de.fau.cs.inf2.tree.evaluation.Main.java

/**
 * Parses data/validation/validation.json and prints the total number of
 * votes.//  ww  w  .j a va2  s.  co m
 */
private static void readValidationDataAndPrint(File path) {
    File validationDir = new File(path, "/validation/");
    File validationInputFile = new File(validationDir, "val_input.json");
    ObjectMapper mapper = TreeEvalIO.createJSONMapper();
    try {
        ValidationInputSummary summary = mapper.readValue(validationInputFile, ValidationInputSummary.class);
        int sum = -1;
        if (summary != null && summary.validations != null) {
            sum = summary.validations.size();
        }
        System.out.println("Validation input size: " + sum);
        File[] files = validationDir.listFiles();
        int votes = 0;
        if (files != null) {
            for (File raterDir : files) {
                if (raterDir.isDirectory()) {
                    File rating = new File(raterDir.getAbsolutePath() + "/voting.json");
                    ValidationDecisionList list = mapper.readValue(rating, ValidationDecisionList.class);
                    if (list != null && list.decisions != null) {
                        votes += list.decisions.size();
                    }
                }
            }
        }
        System.out.println("Validation votes: " + votes);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:com.pingcap.tikv.catalog.CatalogTransaction.java

public static <T> T parseFromJson(ByteString json, Class<T> cls) {
    Objects.requireNonNull(json, "json is null");
    Objects.requireNonNull(cls, "cls is null");

    logger.debug(String.format("Parse Json %s : %s", cls.getSimpleName(), json.toStringUtf8()));
    ObjectMapper mapper = new ObjectMapper();
    try {//from w ww.  ja  v a  2  s.  c  o m
        return mapper.readValue(json.toStringUtf8(), cls);
    } catch (JsonParseException | JsonMappingException e) {
        String errMsg = String.format("Invalid JSON value for Type %s: %s\n", cls.getSimpleName(),
                json.toStringUtf8());
        throw new TiClientInternalException(errMsg, e);
    } catch (Exception e1) {
        throw new TiClientInternalException("Error parsing Json", e1);
    }
}

From source file:org.dasein.cloud.aws.model.DatabaseProvider.java

public static DatabaseProvider fromFile(String filename, String providerId) throws InternalException {
    try {/*w w  w . j a v a2 s  . c o m*/
        ObjectMapper om = new ObjectMapper();
        URL url = om.getClass().getResource(filename);
        DatabaseProvider[] providers = om.readValue(url, DatabaseProvider[].class);
        for (DatabaseProvider provider : providers) {
            if (provider.provider.equalsIgnoreCase(providerId)) {
                return provider;
            }
        }
    } catch (IOException e) {
        throw new InternalException("Unable to read stream", e);
    }
    throw new InternalException("Unable to find " + providerId + " provider configuration in " + filename);
}

From source file:de.elanev.studip.android.app.backend.datamodel.Settings.java

public static Settings fromJson(String jsonString) {
    ObjectMapper mapper = new ObjectMapper();
    Settings settings = null;//from   www .j  a  v  a2s  .  c  o m
    try {
        settings = mapper.readValue(jsonString, Settings.class);
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return settings;
}