@JsonIgnore public String getAsJSON() { ObjectMapper mapper = new ObjectMapper(); return mapper.writeValueAsString(this) ; }
@JsonIgnoreProperties({"foobar"}) public static class Foo { public String foo = "a"; public String bar = "b"; public String foobar = "c"; } //Test code ObjectMapper mapper = new ObjectMapper(); Foo foo = new Foo(); foo.foobar = "foobar"; foo.foo = "Foo"; String out = mapper.writeValueAsString(foo); Foo f = mapper.readValue(out, Foo.class);
import java.io.File; import org.codehaus.jackson.annotate.JsonIgnore; import org.codehaus.jackson.map.ObjectMapper; public class Foo { String value; public String getValue() {return value;} public void setValue(String value) {this.value = value;} @JsonIgnore public void setValue(int value) {this.value = String.valueOf(value);} public static void main(String[] args) throws Exception { ObjectMapper mapper = new ObjectMapper(); Foo foo = mapper.readValue(new File("input.json"), Foo.class); System.out.println(mapper.writeValueAsString(foo)); } }
@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 testGetNotThere() throws Exception { Map<String, Object> lookupMap = new HashMap<>(); lookupMap.put("testMockForGetNotThere", container); String strResult = mapper.writeValueAsString(lookupMap); Request request = new Request(HttpMethod.GET, new URL("http://localhost:1234/xx")); expect(config.getLookupTier()).andReturn(LOOKUP_TIER).anyTimes(); replay(config); expect(druidLeaderClient.makeRequest( HttpMethod.GET, "/druid/coordinator/v1/lookups/config/lookupTier?detailed=true" )) .andReturn(request); FullResponseHolder responseHolder = new FullResponseHolder( HttpResponseStatus.OK, EasyMock.createNiceMock(HttpResponse.class), new StringBuilder().append(strResult) ); expect(druidLeaderClient.go(request)).andReturn(responseHolder); replay(druidLeaderClient); lookupReferencesManager.start(); Assert.assertNull(lookupReferencesManager.get("notThere")); }
public static String getFormattedReplication( String strategy, String strategyOptions) throws JsonProcessingException { Map<String, String> replicationSettings = new HashMap<>(); replicationSettings.put("class", strategy); String[] strategyOptionsSplit = strategyOptions.split(","); for ( String option : strategyOptionsSplit){ String[] splitOptions = option.split(":"); replicationSettings.put(splitOptions[0], splitOptions[1]); } return mapper.writeValueAsString(replicationSettings).replace("\"", "'"); }
private void update(Map<String, Object> externalIdMap, Map<String, Object> output, Status status) throws Exception { Map<String, Object> outputMap = new HashMap<>(); outputMap.put("externalId", objectMapper.writeValueAsString(externalIdMap)); outputMap.putAll(output); Message msg = new Message(UUID.randomUUID().toString(), objectMapper.writeValueAsString(outputMap), null); ObservableQueue queue = queues.get(status); if(queue == null) { throw new IllegalArgumentException("There is no queue for handling " + status.toString() + " status"); } queue.publish(Arrays.asList(msg)); } }
private void resolveObjectToColumns(Map<String, String> columnData, Object value) { if (value instanceof PdxInstance) { resolvePdxToColumns(columnData, (PdxInstance) value); } else if (value instanceof Struct) { resolveStructToColumns(columnData, (StructImpl) value); } else { ObjectMapper mapper = new ObjectMapper(); JsonNode node = mapper.valueToTree(value); node.fieldNames().forEachRemaining(field -> { try { columnData.put(field, mapper.writeValueAsString(node.get(field))); } catch (JsonProcessingException e) { columnData.put(field, e.getMessage()); } }); } }
public static void main(String... args) throws Exception { ObjectMapper mapper = new ObjectMapper(); Response r1 = new Response("Error", "Some error", 20); System.out.println(mapper.writeValueAsString(r1)); Response r2 = new Response("Error", "Some error", "some string"); System.out.println(mapper.writeValueAsString(r2)); }
@Test public void autowiredSerializer() throws JsonProcessingException { User user = new User("bob"); String json = this.objectMapper.writeValueAsString(user); assertEquals("{\"username\":\"BOB\"}", json); }
private Handler<Message<String>> allProductsHandler(ProductService service) { // It is important to use an executeBlocking construct here // as the service calls are blocking (dealing with a database) return msg -> vertx.<String>executeBlocking(future -> { try { future.complete(mapper.writeValueAsString(service.getAllProducts())); } catch (JsonProcessingException e) { System.out.println("Failed to serialize result"); future.fail(e); } }, result -> { if (result.succeeded()) { msg.reply(result.result()); } else { msg.reply(result.cause().toString()); } }); }
@Test public void applicationContextAwaretypeResolverBuilder() throws JsonProcessingException { this.objectMapper.writeValueAsString(new Group()); assertTrue(CustomTypeResolverBuilder.isAutowiredFiledInitialized); }
@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()); } }
@Test public void testRemoveNonExisting() throws Exception { Map<String, Object> lookupMap = new HashMap<>(); lookupMap.put("testMockForRemoveNonExisting", container); String strResult = mapper.writeValueAsString(lookupMap); Request request = new Request(HttpMethod.GET, new URL("http://localhost:1234/xx")); expect(config.getLookupTier()).andReturn(LOOKUP_TIER).anyTimes(); replay(config); expect(druidLeaderClient.makeRequest( HttpMethod.GET, "/druid/coordinator/v1/lookups/config/lookupTier?detailed=true" )) .andReturn(request); FullResponseHolder responseHolder = new FullResponseHolder( HttpResponseStatus.OK, EasyMock.createNiceMock(HttpResponse.class), new StringBuilder().append(strResult) ); expect(druidLeaderClient.go(request)).andReturn(responseHolder); replay(druidLeaderClient); lookupReferencesManager.start(); lookupReferencesManager.remove("test"); lookupReferencesManager.handlePendingNotices(); }
@JsonCreator public InlineSchemasAvroBytesDecoder( @JacksonInject @Json ObjectMapper mapper, @JsonProperty("schemas") Map<String, Map<String, Object>> schemas ) throws Exception { Preconditions.checkArgument( schemas != null && schemas.size() > 0, "at least one schema must be provided in schemas attribute" ); this.schemas = schemas; schemaObjs = new HashMap<>(schemas.size()); for (Map.Entry<String, Map<String, Object>> e : schemas.entrySet()) { int id = Integer.parseInt(e.getKey()); Map<String, Object> schema = e.getValue(); String schemaStr = mapper.writeValueAsString(schema); LOGGER.debug("Schema string [%s] = [%s]", id, schemaStr); schemaObjs.put(id, new Schema.Parser().parse(schemaStr)); } }
Coordinates c = new Coordinates(); c.setRed((byte) 5); ObjectMapper mapper = new ObjectMapper(); System.out.println("Serialization: " + mapper.writeValueAsString(c)); Coordinates r = mapper.readValue("{\"red\":25}",Coordinates.class); System.out.println("Deserialization: " + r.getR());
ObjectMapper mapper = new ObjectMapper(); mapper.getFactory().configure(JsonGenerator.Feature.ESCAPE_NON_ASCII, true); ObjectNode node = mapper.getNodeFactory().objectNode(); node.put("field1", "Maël Hörz"); System.out.println(mapper.writeValueAsString(node));
@Test // SPR-13975 public void defaultUseWrapper() throws JsonProcessingException { ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.xml().defaultUseWrapper(false).build(); assertNotNull(objectMapper); assertEquals(XmlMapper.class, objectMapper.getClass()); ListContainer<String> container = new ListContainer<>(Arrays.asList("foo", "bar")); String output = objectMapper.writeValueAsString(container); assertThat(output, containsString("<list>foo</list><list>bar</list></ListContainer>")); }
@Test public void applicationContextAwareTypeIdResolver() throws JsonProcessingException { this.objectMapper.writeValueAsString(new Group()); assertTrue(CustomTypeIdResolver.isAutowiredFiledInitialized); }
public class PojoTest { ObjectMapper mapper = new ObjectMapper(); @Test public void test() throws IOException { Pojo pojo = new Pojo("{\"foo\":18}"); String output = mapper.writeValueAsString(pojo); assertThat(output).isEqualTo("{\"json\":{\"foo\":18}}"); Pojo deserialized = mapper.readValue(output, Pojo.class); assertThat(deserialized.json.toString()).isEqualTo("{\"foo\":18}"); // deserialized.json == {"foo":18} } }