List of usage examples for com.fasterxml.jackson.databind ObjectMapper writeValueAsString
@SuppressWarnings("resource") public String writeValueAsString(Object value) throws JsonProcessingException
From source file:com.arpnetworking.jackson.ObjectMapperFactoryTest.java
@Test public void testGetInstanceConversion() throws IOException { final String expectedJson = "{}"; final ObjectMapper objectMapper = ObjectMapperFactory.getInstance(); final JsonNode jsonNode = objectMapper.readValue(expectedJson, JsonNode.class); final String actualJson = objectMapper.writeValueAsString(jsonNode); Assert.assertEquals(expectedJson, actualJson); }
From source file:eu.trentorise.opendata.commons.test.jackson.JacksonTest.java
/** * Shows that nasty Jackson deserializes "" into null instead of * {@link Locale.ROOT} !!!// w w w . j ava 2 s . co m * */ @Test(expected = AssertionError.class) public void testLocaleDeser() throws JsonProcessingException, IOException { ObjectMapper om = new ObjectMapper(); String json = om.writeValueAsString(new RootLocale()); LOG.log(Level.FINE, "json = {0}", json); RootLocale res = om.readValue(json, RootLocale.class); assertNotNull(res.locale); assertEquals(Locale.ROOT, res.locale); }
From source file:com.arpnetworking.jackson.ObjectMapperFactoryTest.java
@Test public void testNewInstanceConversion() throws IOException { final String expectedJson = "{}"; final ObjectMapper objectMapper = ObjectMapperFactory.createInstance(); final JsonNode jsonNode = objectMapper.readValue(expectedJson, JsonNode.class); final String actualJson = objectMapper.writeValueAsString(jsonNode); Assert.assertEquals(expectedJson, actualJson); }
From source file:org.springframework.security.jackson2.UserDeserializerTests.java
@Test public void serializeUserTest() throws JsonProcessingException, JSONException { ObjectMapper mapper = buildObjectMapper(); User user = new User("admin", "1234", Collections.singletonList(new SimpleGrantedAuthority("USER_ROLE"))); String userJson = mapper.writeValueAsString(user); String expectedJson = "{\"@class\": \"org.springframework.security.core.userdetails.User\", \"username\": \"admin\", \"password\": \"1234\", \"accountNonExpired\": true, \"accountNonLocked\": true, \"credentialsNonExpired\": true, \"enabled\": true, \"authorities\": [\"java.util.Collections$UnmodifiableSet\", [{\"@class\": \"org.springframework.security.core.authority.SimpleGrantedAuthority\", \"role\": \"USER_ROLE\"}]]}"; JSONAssert.assertEquals(expectedJson, userJson, true); }
From source file:uk.ac.surrey.ee.iot.fiware.ngsi9.notify.NotifierAtRegistration.java
@Override public void run() { List<SubscribeContextAvailabilityRequest> subReq = SubscriptionStoreAccess.matchRegToSubs(regReq); int subReqListSize = subReq.size(); List<ContextRegistration> cr = regReq.getContextRegistration(); //iterate through each subscription for (int i = 0; i < subReqListSize; i++) { NotifyContextAvailabilityRequest ncar = new NotifyContextAvailabilityRequest(); List<ContextRegistrationResponse> crrl = new ArrayList<>(); int crListSize = cr.size(); //iterate through each context registration for (int j = 0; j < crListSize; j++) { ContextRegistrationResponse crr = new ContextRegistrationResponse(); crr.setContextRegistration(cr.get(j)); crrl.add(crr);/*from w ww . j a v a 2 s . c o m*/ } ncar.getContextRegistrationResponse().addAll(crrl); ncar.setSubscriptionId(subReq.get(i).getSubscriptionId()); //serialize request String notifMsg = null; ObjectMapper objectMapper = new ObjectMapper(); objectMapper.enable(SerializationFeature.INDENT_OUTPUT); try { notifMsg = objectMapper.writeValueAsString(ncar); } catch (JsonProcessingException ex) { Logger.getLogger(Resource02_Discovery.class.getName()).log(Level.SEVERE, null, ex); } //notify subscriber String callbackUrl = subReq.get(i).getReference(); ClientResource ngsiClient = new ClientResource(callbackUrl); ngsiClient.accept(MediaType.APPLICATION_JSON); String payload = notifMsg; try { ngsiClient.post(payload).write(System.out); //Response is not handled for now } catch (IOException ex) { Logger.getLogger(NotifierAtRegistration.class.getName()).log(Level.SEVERE, null, ex); } } }
From source file:com.samlikescode.stackoverflow.questions.q29630371.PersonTest.java
@Test public void serializePersonTest() throws JsonProcessingException { // set up test data including parent properties Person person = new Person("Database property 1", "Database property 2"); person.setIndex("1"); person.setFirstName("Joe"); person.setLastName("Bob"); // register the mix in ObjectMapper om = new ObjectMapper().addMixIn(Person.class, PersonMixIn.class); // translate object to JSON string using Jackson String json = om.writeValueAsString(person); assertFalse(json.contains("dbPropertyA")); assertFalse(json.contains("dbPropertyB")); assertFalse(json.contains("index")); System.out.println(json); }//w w w. ja v a 2s .co m
From source file:marshalsec.Jackson.java
/** * {@inheritDoc}//from w w w .j a v a 2 s. c o m * * @see marshalsec.MarshallerBase#marshal(java.lang.Object) */ @Override public String marshal(Object o) throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.enableDefaultTyping(); return mapper.writeValueAsString(o); }
From source file:ch.icclab.cyclops.resource.impl.RateStatusResource.java
/** * Build the static rate of a resource//w w w .j ava 2 s . c o m * * Pseudo Code * 1. Get the latest static rates from a list * 2. Construct the response * 3. Return the json string * * @return Representation */ private Representation buildStaticRateResponse() { String jsonStr = null; RateStatusResponse response = new RateStatusResponse(); ObjectMapper mapper = new ObjectMapper(); response.setRate_policy("static"); response.setRate(Load.getStaticRate()); try { jsonStr = mapper.writeValueAsString(response); } catch (JsonProcessingException e) { e.printStackTrace(); } JsonRepresentation jsonResp = new JsonRepresentation(jsonStr); return jsonResp; }
From source file:org.commonjava.cartographer.result.ProjectPathTest.java
@Test public void jsonRoundTrip() throws Exception { ProjectVersionRef ref = new SimpleProjectVersionRef("org.foo", "bar", "1"); ProjectPath in = new ProjectPath(Collections.singletonList(new SimpleParentRelationship( URI.create("http://nowhere.com"), ref, new SimpleProjectVersionRef("org.dep", "project", "1.1")))); ObjectMapper mapper = new ObjectMapper(); mapper.registerModules(new ProjectVersionRefSerializerModule(), new ProjectRelationshipSerializerModule()); mapper.enable(SerializationFeature.INDENT_OUTPUT); String json = mapper.writeValueAsString(in); System.out.println(json);/*from w w w. j ava 2s. c o m*/ ProjectPath out = mapper.readValue(json, ProjectPath.class); }
From source file:com.blockwithme.lessobjects.util.JSONParser.java
/** * To json string.//from ww w .jav a 2 s .c om * * @return the string */ @SuppressWarnings("null") public String toJSONString() { if (jsonString == null) { if (fromSchema) { try { final ObjectWriter writer = initMapper(); jsonString = writer.writeValueAsString(schema); } catch (final JsonProcessingException jpe) { throw new IllegalStateException(jpe.getMessage(), jpe); } } else { try { if (format == SchemaFormat.JSON) { jsonString = jsonOrXMLString; } else { if (xmlString == null) { xmlString = jsonOrXMLString; } final XmlMapper xmlMapper = new XmlMapper(); schema = xmlMapper.readValue(jsonOrXMLString, StructSchema.class); final ObjectMapper jsonMapper = new ObjectMapper(); jsonString = jsonMapper.writeValueAsString(schema); } } catch (final IOException e) { throw new IllegalStateException(e.getMessage(), e); } } } return jsonString; }