Java Code Examples for com.fasterxml.jackson.databind.ObjectMapper.readValue()

The following are Jave code examples for showing how to use readValue() of the com.fasterxml.jackson.databind.ObjectMapper class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: swordfish-service   File: RestoreCommandGatewayRestController.java   View Source Code Vote up 7 votes
@PostMapping("/stack-events")
public ResponseEntity<String> event(@RequestBody String payload) {
    try {
        String result = java.net.URLDecoder.decode(payload, "UTF-8");
        ObjectMapper objectMapper = new ObjectMapper();

        StackEvent stackEvent = objectMapper.readValue(result, StackEvent.class);
        stackEvent.setUserToken(authenticationService.getCurrentToken());

        payload = jsonTransformService.write(stackEvent);

        this.queueMessagingTemplate.send(queue,
                MessageBuilder.withPayload(payload).build());
    } catch (IOException e) {
        log.error(e.getLocalizedMessage());
    }

    return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
 
Example 2
Project: spring-cloud-skipper   File: Status.java   View Source Code Vote up 6 votes
@JsonIgnore
public List<AppStatus> getAppStatusList() {
	try {
		ObjectMapper mapper = new ObjectMapper();
		mapper.addMixIn(AppStatus.class, AppStatusMixin.class);
		mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		SimpleModule module = new SimpleModule("CustomModel", Version.unknownVersion());
		SimpleAbstractTypeResolver resolver = new SimpleAbstractTypeResolver();
		resolver.addMapping(AppInstanceStatus.class, AppInstanceStatusImpl.class);
		module.setAbstractTypes(resolver);
		mapper.registerModule(module);
		TypeReference<List<AppStatus>> typeRef = new TypeReference<List<AppStatus>>() {
		};
		if (this.platformStatus != null) {
			return mapper.readValue(this.platformStatus, typeRef);
		}
		return new ArrayList<AppStatus>();
	}
	catch (Exception e) {
		throw new IllegalArgumentException("Could not parse Skipper Platfrom Status JSON:" + platformStatus, e);
	}
}
 
Example 3
Project: r2-streamer-java   File: TestActivity.java   View Source Code Vote up 6 votes
@Override
protected EpubPublication doInBackground(String... urls) {
    String strUrl = urls[0];

    try {
        URL url = new URL(strUrl);
        URLConnection urlConnection = url.openConnection();
        InputStream inputStream = urlConnection.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder stringBuilder = new StringBuilder();
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            stringBuilder.append(line);
        }

        Log.d("TestActivity", "EpubPublication => " + stringBuilder.toString());

        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        return objectMapper.readValue(stringBuilder.toString(), EpubPublication.class);
    } catch (IOException e) {
        Log.e(TAG, "SpineListTask error " + e);
    }
    return null;
}
 
Example 4
Project: twitch4j   File: CommandHandler.java   View Source Code Vote up 6 votes
/**
 * Load Dynamic Commands
 */
public void loadDynamicCommands() {
	purgeDynamicCommands();

	try {
		// Load commands from File
		ObjectMapper mapper = new ObjectMapper();
		List<DynamicCommand> loadedCommands = mapper.readValue(getCommandSaveFile(), new TypeReference<ArrayList<DynamicCommand>>() {
		});

		// Register Commands
		for (Command cmd : loadedCommands) {
			registerCommand(cmd);
		}
	} catch (Exception ex) {
		// we can ignore this, no dynamic content's saved
		if (ex.getMessage().contains("No content")) {
			return;
		}

		ex.printStackTrace();
	}
}
 
Example 5
Project: swagger-java-diff-cli   File: RuleParserV1.java   View Source Code Vote up 6 votes
public Map<String, Rule> parseCustomRules(String fileName) throws IOException {
    Map<String, Rule> rules = gatherRules();
    if (null != fileName) {
        File file = new File(fileName);
        ObjectMapper objectMapper = new ObjectMapper();
        TypeReference<HashMap<String, Boolean>> typeReference
                = new TypeReference<HashMap<String, Boolean>>() {
        };
        Map<String, Boolean> customRules = objectMapper.readValue(file, typeReference);

        for (Map.Entry<String, Boolean> entry : customRules.entrySet()) {
            if (rules.containsKey(entry.getKey().toLowerCase())) {
                Rule rule = rules.get(entry.getKey());
                rule.setBreakingChange(entry.getValue());
                rules.put(CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, rule.getRuleName()), rule);
                LOGGER.info("Submited Rule " + rule.getRuleName() + " to " + entry.getValue());
            }
        }
    }
    return rules;
}
 
Example 6
Project: r2-streamer-java   File: TestActivity.java   View Source Code Vote up 6 votes
@Override
protected SearchQueryResults doInBackground(String... urls) {
    String strUrl = urls[0];
    try {
        URL url = new URL(strUrl);
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("GET");
        InputStream inputStream = urlConnection.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder stringBuilder = new StringBuilder();
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            stringBuilder.append(line);
        }

        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        return objectMapper.readValue(stringBuilder.toString(), SearchQueryResults.class);
    } catch (IOException e) {
        Log.e(TAG, "SearchListTask IOException " + e.toString());
    }
    return null;
}
 
Example 7
Project: spring-credhub   File: CredHubDemoController.java   View Source Code Vote up 6 votes
private ServicesData buildServicesData(String credHubReferenceName) throws IOException {
	String vcapServices = "{" +
			"  \"service-offering\": [" +
			"   {" +
			"    \"credentials\": {" +
			"      \"credhub-ref\": \"((" + credHubReferenceName + "))\"" +
			"    }," +
			"    \"label\": \"service-offering\"," +
			"    \"name\": \"service-instance\"," +
			"    \"plan\": \"standard\"," +
			"    \"tags\": [" +
			"     \"cloud-service\"" +
			"    ]," +
			"    \"volume_mounts\": []" +
			"   }" +
			"  ]" +
			"}";

	ObjectMapper mapper = new ObjectMapper();
	return mapper.readValue(vcapServices, ServicesData.class);
}
 
Example 8
Project: seldon-core   File: TestJsonParse.java   View Source Code Vote up 6 votes
@Test
public void multiDimTest() throws JsonProcessingException, IOException
{
	String json = "{\"request\":{\"values\":[[1.0]]}}";

	System.out.println(json);
	ObjectMapper mapper = new ObjectMapper();
	JsonFactory factory = mapper.getFactory();
	JsonParser parser = factory.createParser(json);
	JsonNode j = mapper.readTree(parser);
	JsonNode values = j.get("request").get("values");
	
	double[][] v = mapper.readValue(values.toString(),double[][].class);
	double[] vs = Doubles.concat(v);
	int[] shape = {v.length,v[0].length };
	((ObjectNode) j.get("request")).replace("values",mapper.valueToTree(vs));
	((ObjectNode) j.get("request")).set("shape",mapper.valueToTree(shape));
	System.out.println(j.toString());
}
 
Example 9
Project: devops-cstack   File: JsonConverter.java   View Source Code Vote up 5 votes
public static Server getServer(String response) {
	Server server = new Server();
	ObjectMapper mapper = new ObjectMapper();
	try {
		server = mapper.readValue(response, Server.class);
	} catch (IOException e) {

		e.printStackTrace();
	}
	return server;
}
 
Example 10
Project: devops-cstack   File: JsonConverter.java   View Source Code Vote up 5 votes
public static User getUser(String response) {
	User user = new User();
	ObjectMapper mapper = new ObjectMapper();
	try {
		user = mapper.readValue(response, User.class);
	} catch (IOException e) {
		e.printStackTrace();
	}
	return user;
}
 
Example 11
Project: pyplyn   File: SimpleConnectorProvider.java   View Source Code Vote up 5 votes
/**
 * Reads all connectors from file
 *   and returns a list of all defined connectors, without loading the password bytes
 *
 * @throws IOException on any deserialization errors
 */
private List<EndpointConnector> readFromConnectorsFile(ObjectMapper mapper, String connectorPath) throws IOException {
    // first attempt to deserialize the connectors
    EndpointConnector[] connectors = mapper.readValue(loadResourceInsecure(connectorPath), Connector[].class);

    return CollectionUtils.immutableOrEmptyList(Arrays.asList(connectors));
}
 
Example 12
Project: javaGMR   File: GamepaneController.java   View Source Code Vote up 5 votes
@FXML
public void openEditor() {
    File noteFile = new File("notes/" + this.game.getGameid() + ".json");
    try {
        Note note;
        if (noteFile.exists()) {
            ObjectMapper mapper = new ObjectMapper();
            note = mapper.readValue(noteFile, Note.class);
        } else {
            note = new Note(this.game.getGameid());
            note.setText("");
        }
        Scene scene = this.getScene("texteditor.fxml");
        TexteditorController tec = (TexteditorController) scene.getUserData();
        tec.constructView(note);
        Stage editor = new Stage();
        editor.setOnHiding(event -> {
            tec.saveOnExit();
        });
        editor.setScene(scene);
        editor.showAndWait();
        if(hasNote()){
            btNoteEditor.getStyleClass().add("primary");
             btNoteEditor.applyCss();
        }else{
            btNoteEditor.getStyleClass().remove("primary");
            btNoteEditor.applyCss();
        }
    } catch (IOException ex) {

    }
}
 
Example 13
Project: javaGMR   File: GamepaneController.java   View Source Code Vote up 5 votes
private boolean hasNote(){
    File noteFile = new File("notes/" + this.game.getGameid() + ".json");
    
    if (!noteFile.exists())
            return false;
    else {
        try {
            ObjectMapper mapper = new ObjectMapper();
            Note note = mapper.readValue(noteFile, Note.class);
            return !note.getText().equals("");
        } catch (IOException ex) {
        }
    }
    return false;
}
 
Example 14
Project: servicebuilder   File: ProblemResponseParserTest.java   View Source Code Vote up 5 votes
@Test
public void serializeAndDeserializeJson() throws IOException {
    ObjectMapper objectMapper = new ObjectMapper();
    String jsonString = objectMapper.writeValueAsString(problemResponse);

    ProblemResponse value = objectMapper.readValue(jsonString, ProblemResponse.class);
    assertThat(value, is(equalTo(problemResponse)));
}
 
Example 15
Project: research-graphql   File: OrderMapperTest.java   View Source Code Vote up 5 votes
@Test
public void testOrderJpaToOrderDto() throws IOException {

    OrderForm orderJpa = OrderForm.builder()
            .id("orderJpa-1")
            .userId("user-1")
            .status(OrderDto.Status.SUBMITTED)
            .items(ImmutableList.of(
                    OrderItem.builder()
                            .productId("product-1")
                            .quantity(10)
                            .build()
            ))
            .build();

    OrderDto orderDto = mapper.toOrderDto(orderJpa);

    softly.then(orderDto.getId()).isEqualTo(orderJpa.getId());
    softly.then(orderDto.getUserId()).isEqualTo(orderJpa.getUserId());
    softly.then(orderDto.getStatus()).isEqualTo(orderJpa.getStatus());
    softly.then(orderDto.getItems())
            .isNotNull()
            .hasSize(1);
    softly.then(orderDto.getItems().get(0).getProductId()).isEqualTo("product-1");
    softly.then(orderDto.getItems().get(0).getQuantity()).isEqualTo(10);

    ObjectMapper jsonMapper = new ObjectMapper();
    String jsonOrderDto = jsonMapper.writeValueAsString(orderDto);
    OrderDto pojoOrderDto = jsonMapper.readValue(jsonOrderDto, OrderDto.class);

    softly.then(pojoOrderDto.getId()).isEqualTo(orderJpa.getId());
    softly.then(pojoOrderDto.getUserId()).isEqualTo(orderJpa.getUserId());
    softly.then(pojoOrderDto.getStatus()).isEqualTo(orderJpa.getStatus());
    softly.then(pojoOrderDto.getItems())
            .isNotNull()
            .hasSize(1);
    softly.then(pojoOrderDto.getItems().get(0).getProductId()).isEqualTo("product-1");
    softly.then(pojoOrderDto.getItems().get(0).getQuantity()).isEqualTo(10);

}
 
Example 16
Project: tikv-client-lib-java   File: TiConstantTest.java   View Source Code Vote up 5 votes
@Test
public void greaterThanTest() throws Exception {
  ObjectMapper mapper = new ObjectMapper();
  TiTableInfo tableInfo = mapper.readValue(TiTableInfoTest.tableJson, TiTableInfo.class);
  GreaterThan g = new GreaterThan(TiColumnRef.create("c1", tableInfo), TiConstant.create(1.12));
  Expr ge = g.toProto();
  assertEquals(2, ge.getChildrenCount());
  double expected = RealType.readDouble(new CodecDataInput(ge.getChildren(1).getVal()));
  assertEquals(1.12, expected, 0.00001);
}
 
Example 17
Project: loom   File: AggregationManagerTest.java   View Source Code Vote up 4 votes
private <T> T fromJson(final String json, final Class<T> classObj) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    T recovered = mapper.readValue(json, classObj);
    return recovered;
}
 
Example 18
Project: redg   File: JsonFileExplicitAttributeDecider.java   View Source Code Vote up 4 votes
public JsonFileExplicitAttributeDecider(Reader reader) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    TypeReference<HashMap<String, JsonExplicitModel>> typeRef = new TypeReference<HashMap<String, JsonExplicitModel>>() {
    };
    explicitDataByTableRegex = mapper.readValue(reader, typeRef);
}
 
Example 19
Project: mobile-store   File: IndexV1Updater.java   View Source Code Vote up 4 votes
private Map<String, String[]> parseRequests(ObjectMapper mapper, JsonParser parser) throws IOException {
    TypeReference<HashMap<String, String[]>> typeRef = new TypeReference<HashMap<String, String[]>>() {
    };
    parser.nextToken(); // START_OBJECT
    return mapper.readValue(parser, typeRef);
}
 
Example 20
Project: openmensa-java   File: JsonConverter.java   View Source Code Vote up 4 votes
public static CanteenPojo canteenFromJson(String json) throws IOException {
    ObjectMapper objectMapper = new ObjectMapper();
    return objectMapper.readValue(json, CanteenPojo.class);
}