ObjectMapper mapper = new ObjectMapper(); Person user = mapper.readValue("{\"name\": \"John\"}", Person.class); System.out.println(user.name); //John
public void testJackson() throws IOException { ObjectMapper mapper = new ObjectMapper(); File from = new File("albumnList.txt"); TypeReference<HashMap<String,Object>> typeRef = new TypeReference<HashMap<String,Object>>() {}; HashMap<String,Object> o = mapper.readValue(from, typeRef); System.out.println("Got " + o); }
public static <T> T deserialize(byte[] data, Class<T> cls) { T obj = null; try { obj = objMapper.readValue(data, cls); } catch (IOException e) { throw new IllegalStateException(e.getMessage(), e); } return obj; }
@Test public void testSerde() throws IOException { final List<Rule> rules = Collections.singletonList(testRule); final String json = MAPPER.writeValueAsString(rules); final List<Rule> fromJson = MAPPER.readValue(json, new TypeReference<List<Rule>>(){}); assertEquals(rules, fromJson); } }
@Test public void testReplace() throws Exception { Map<String, Object> map = new HashMap<>(); map.put("name", "conductor"); map.put("version", 2); map.put("externalId", "{\"taskRefName\":\"t001\",\"workflowId\":\"w002\"}"); Map<String, Object> input = new HashMap<>(); input.put("k1", "${$.externalId}"); input.put("k4", "${name}"); input.put("k5", "${version}"); Object jsonObj = objectMapper.readValue(objectMapper.writeValueAsString(map), Object.class); Map<String, Object> replaced = parametersUtils.replace(input, jsonObj); assertNotNull(replaced); System.out.println("testNoExpand(): " + replaced); assertEquals("{\"taskRefName\":\"t001\",\"workflowId\":\"w002\"}", replaced.get("k1")); assertEquals("conductor", replaced.get("k4")); assertEquals(2, replaced.get("k5")); }
@Test public void testArrayValue() throws Exception { userNeedColNames = new String[] { "userMentionEntities", "mediaEntities" }; List<TblColRef> allCol = mockupTblColRefList(); TimedJsonStreamParser parser = new TimedJsonStreamParser(allCol, null); Object msg = mapper.readValue(new File(jsonFilePath), mapType); HashMap<String, Object> map = (HashMap<String, Object>) msg; Object array = map.get("mediaEntities"); ByteBuffer buffer = getJsonByteBuffer(msg); List<StreamingMessageRow> msgList = parser.parse(buffer); List<String> result = msgList.get(0).getData(); System.out.println(result); }
StateConfig getStateConfig(Map<String, Object> topoConf) throws Exception { StateConfig stateConfig; String providerConfig; ObjectMapper mapper = new ObjectMapper(); mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY); if (topoConf.containsKey(Config.TOPOLOGY_STATE_PROVIDER_CONFIG)) { providerConfig = (String) topoConf.get(Config.TOPOLOGY_STATE_PROVIDER_CONFIG); stateConfig = mapper.readValue(providerConfig, StateConfig.class); } else { stateConfig = new StateConfig(); } return stateConfig; }
ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(module); User user = mapper.readValue(new File("test.json"), User.class);
@Override public Segment getSegment(DataSegment segment) throws SegmentLoadingException { File segmentFiles = getSegmentFiles(segment); File factoryJson = new File(segmentFiles, "factory.json"); final SegmentizerFactory factory; if (factoryJson.exists()) { try { factory = jsonMapper.readValue(factoryJson, SegmentizerFactory.class); } catch (IOException e) { throw new SegmentLoadingException(e, "%s", e.getMessage()); } } else { factory = new MMappedQueryableSegmentizerFactory(indexIO); } return factory.factorize(segment, segmentFiles); }
/** * Converts a JSON String into a Sim object using the provided ObjectMapper. * * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Sim object represented by the provided JSON */ public static Sim fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Sim.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { throw new ApiConnectionException(e.getMessage(), e); } }
@Test public void optMap() throws Exception { System.err.println("0"); UseOptionalCollections<Boolean> value = objectMapper.readValue("{\"maybeMap\":{\"a\":true},\"as\":[\"b\"]}", new TypeReference<UseOptionalCollections<Boolean>>() {}); UseOptionalCollections<Boolean> map = ImmutableUseOptionalCollections.<Boolean>builder() .putMaybeMap("a", true) .addA("b") .build(); check(value).is(map); check(value.maybeMap()).is(Optional.of(ImmutableMap.of("a", true))); check(value.as()).is(Optional.of(ImmutableList.of("b"))); check(value.bs()).is(Optional.empty()); } }
@Test public void testIsAuthenticationInfoJSONWrappable() { try { final AuthenticationInfo authenticationInfo = new AuthenticationInfo("user", "password", "http://server:8080/tfs", "name"); final String str = mapper.writeValueAsString(authenticationInfo); final AuthenticationInfo restored = mapper.readValue(str, AuthenticationInfo.class); } catch (JsonProcessingException e) { Assert.fail("Failed converting AuthenticationInfo to String or vice versa: " + e.getMessage()); } catch (IOException e) { Assert.fail("Failed to read AuthenticationInfo object from String: " + e.getMessage()); } } }
private <T> void assertEqualsJsonResponse(Response expected, Response actual, Class<T> entityClass) throws IOException { ObjectMapper objectMapper = new ObjectMapper(); T entityFromExpected = objectMapper.readValue((String) expected.getEntity(), entityClass); T actualFromExpected = objectMapper.readValue((String) expected.getEntity(), entityClass); assertEquals(entityFromExpected, actualFromExpected); assertEquals(expected.getStatus(), actual.getStatus()); assertTrue(expected.getHeaders().equalsIgnoreValueOrder(actual.getHeaders())); } }
private List<AggregatorFactory> getAggregatorList(String aggregatorJSON) { ComponentLog log = getLogger(); ObjectMapper mapper = new ObjectMapper(null); mapper.registerModule(new AggregatorsModule()); mapper.registerModules(Lists.newArrayList(new SketchModule().getJacksonModules())); mapper.registerModules(Lists.newArrayList(new ApproximateHistogramDruidModule().getJacksonModules())); try { return mapper.readValue( aggregatorJSON, new TypeReference<List<AggregatorFactory>>() { } ); } catch (IOException e) { log.error(e.getMessage(), e); return null; } }
@Test public void testDeserializationSerialization() throws IOException { ObjectMapper mapper = new ObjectMapper(); for (String input : testInputs) { RangePartition partition = mapper.readValue(input, RangePartition.class); String serialized = mapper.writeValueAsString(partition); assertEquals(serialized, input); } } }
private static Map<String,Object> readFragment(File file, String ext) throws IOException { ObjectMapper mapper = new ObjectMapper("json".equals(ext) ? new JsonFactory() : new YAMLFactory()); TypeReference<HashMap<String,Object>> typeRef = new TypeReference<HashMap<String,Object>>() {}; try { Map<String, Object> ret = mapper.readValue(file, typeRef); return ret != null ? ret : new HashMap<String, Object>(); } catch (JsonProcessingException e) { throw new JsonMappingException(String.format("[%s] %s", file, e.getMessage()), e.getLocation(), e); } }
if ("priority".equals(context)) { AnalystClusterRequest task = mapper.readValue(request.getInputStream(), AnalystClusterRequest.class); broker.enqueuePriorityTask(task, response); .readValue(request.getInputStream(), new TypeReference<List<AnalystClusterRequest>>() { }); response.setDetailMessage("Could not decode/encode JSON payload. " + jpex.getMessage()); LOG.info("Error processing JSON from client", jpex); } catch (Exception ex) {
@Test public void testExtremeDoubleValuesSerde() throws IOException { ObjectMapper objectMapper = new ObjectMapper(); for (double value : new double[] {Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY}) { String serialized = objectMapper.writeValueAsString(value); Assert.assertEquals(new Double(value), objectMapper.readValue(serialized, Double.class)); } String negativeInfinityString = objectMapper.writeValueAsString(Double.NaN); Assert.assertTrue(objectMapper.readValue(negativeInfinityString, Double.class).isNaN()); } }
import java.io.File; import java.util.Map; import org.codehaus.jackson.map.ObjectMapper; public class JacksonFoo { public static void main(String[] args) throws Exception { ObjectMapper mapper = new ObjectMapper(); Map map = mapper.readValue(new File("input.json"), Map.class); System.out.println(map); } }
final String json = "{\"date\" : \"2013-05-11\",\"value\" : 123}"; final ObjectMapper mapper = new ObjectMapper() .enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY); final List<Point> points = mapper.readValue(json, new TypeReference<List<Point>>() { }); System.out.println(points);