本文整理汇总了Java中com.fasterxml.jackson.databind.ObjectMapper.readTree方法的典型用法代码示例。如果您正苦于以下问题:Java ObjectMapper.readTree方法的具体用法?Java ObjectMapper.readTree怎么用?Java ObjectMapper.readTree使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类com.fasterxml.jackson.databind.ObjectMapper
的用法示例。
在下文中一共展示了ObjectMapper.readTree方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: treeTraversalSolution
import com.fasterxml.jackson.databind.ObjectMapper; //导入方法依赖的package包/类
public void treeTraversalSolution() {
try {
ObjectMapper mapper = new ObjectMapper();
// use the ObjectMapper to read the json string and create a tree
JsonNode node = mapper.readTree(new File("Persons.json"));
Iterator<String> fieldNames = node.fieldNames();
while (fieldNames.hasNext()) {
JsonNode personsNode = node.get("persons");
Iterator<JsonNode> elements = personsNode.iterator();
while (elements.hasNext()) {
JsonNode element = elements.next();
JsonNodeType nodeType = element.getNodeType();
if (nodeType == JsonNodeType.STRING) {
out.println("Group: " + element.textValue());
}
if (nodeType == JsonNodeType.ARRAY) {
Iterator<JsonNode> fields = element.iterator();
while (fields.hasNext()) {
parsePerson(fields.next());
}
}
}
fieldNames.next();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
示例2: Info
import com.fasterxml.jackson.databind.ObjectMapper; //导入方法依赖的package包/类
@Post
public Map<String, Object> Info(String json) {
Map<String, Object> ret;
ObjectMapper mapper = new ObjectMapper();
try {
JsonNode root = mapper.readTree(json);
String addr = root.get("group_addr").asText();
IMulticastREST mc = (IMulticastREST)getContext().getAttributes().get(IMulticastREST.class.getCanonicalName());
ret = mc.getGroupInfo(addr);
}
catch (IOException e) {
e.printStackTrace();
return new HashMap<String, Object>();
}
return ret;
}
示例3: setUp
import com.fasterxml.jackson.databind.ObjectMapper; //导入方法依赖的package包/类
/**
* Initialize test related variables.
*
* @throws Exception
*/
@Before
public void setUp() throws Exception {
InputStream jsonStream = McastConfigTest.class
.getResourceAsStream("/mcast-config.json");
InputStream invalidJsonStream = McastConfigTest.class
.getResourceAsStream("/mcast-config-invalid.json");
ApplicationId subject = APP_ID;
String key = CoreService.CORE_APP_NAME;
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = mapper.readTree(jsonStream);
JsonNode invalidJsonNode = mapper.readTree(invalidJsonStream);
ConfigApplyDelegate delegate = new MockDelegate();
config = new McastConfig();
config.init(subject, key, jsonNode, mapper, delegate);
invalidConfig = new McastConfig();
invalidConfig.init(subject, key, invalidJsonNode, mapper, delegate);
}
示例4: testExtractTaskPatialMessageSuccess
import com.fasterxml.jackson.databind.ObjectMapper; //导入方法依赖的package包/类
@Test
@SuppressWarnings("resource")
public void testExtractTaskPatialMessageSuccess() throws Exception {
File sampleFileMessageOnly = new File(getClass().getResource("/sample-sqs-message-body-3.json").getFile());
File sampleFileFull = new File(getClass().getResource("/sample-sqs-message-body-4.json").getFile());
String sampleFileContent = new Scanner(sampleFileFull).useDelimiter("\\Z").next();
ObjectMapper mapper = new ObjectMapper();
JsonNode root = mapper.readTree(sampleFileMessageOnly);
TaskMessage taskMessage = MessageExtractor.extractTaskMessage(sampleFileContent);
assertThat(taskMessage.getTask(), equalTo(root.path("task").asText()));
assertThat(taskMessage.getStackPrefix(), equalTo(root.path("stack_prefix").asText()));
JsonNode details = root.path("details");
assertThat(taskMessage.getDetails().getDescriptorFile(), equalTo(details.path("descriptor_file").asText()));
}
示例5: multiDimTest
import com.fasterxml.jackson.databind.ObjectMapper; //导入方法依赖的package包/类
@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());
}
示例6: updateSubnet
import com.fasterxml.jackson.databind.ObjectMapper; //导入方法依赖的package包/类
@PUT
@Path("{subnetUUID}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response updateSubnet(@PathParam("id") String id,
final InputStream input) {
try {
ObjectMapper mapper = new ObjectMapper();
JsonNode subnode = mapper.readTree(input);
Iterable<Subnet> subnets = createOrUpdateByInputStream(subnode);
Boolean result = nullIsNotFound(get(SubnetService.class)
.updateSubnets(subnets), SUBNET_NOT_FOUND);
if (!result) {
return Response.status(INTERNAL_SERVER_ERROR)
.entity(SUBNET_NOT_FOUND).build();
}
return Response.status(203).entity(result.toString()).build();
} catch (Exception e) {
return Response.status(INTERNAL_SERVER_ERROR).entity(e.toString())
.build();
}
}
示例7: testExtractSuccess
import com.fasterxml.jackson.databind.ObjectMapper; //导入方法依赖的package包/类
@Test
@SuppressWarnings("resource")
public void testExtractSuccess() throws Exception {
//Read file into a string
File sampleFile = new File(getClass().getResource("/sample-aem-credentials.json").getFile());
String sampleFileContent = new Scanner(sampleFile).useDelimiter("\\Z").next();
ObjectMapper mapper = new ObjectMapper();
JsonNode root = mapper.readTree(sampleFileContent);
AemCredentials aemCredentials = CredentialsExtractor.extractAemCredentials(sampleFileContent);
assertThat(aemCredentials.getOrchestratorCredentials().getUserName(),
equalTo(CredentialsExtractor.ORCHESTRATOR_USER));
assertThat(aemCredentials.getOrchestratorCredentials().getPassword(),
equalTo(root.path(CredentialsExtractor.ORCHESTRATOR_USER).asText()));
assertThat(aemCredentials.getReplicatorCredentials().getUserName(),
equalTo(CredentialsExtractor.REPLICATOR_USER));
assertThat(aemCredentials.getReplicatorCredentials().getPassword(),
equalTo(root.path(CredentialsExtractor.REPLICATOR_USER).asText()));
}
示例8: initializeFromJson
import com.fasterxml.jackson.databind.ObjectMapper; //导入方法依赖的package包/类
boolean initializeFromJson(final String json) {
try {
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = mapper.readTree(json);
this.userNameToUser = new HashMap<>();
Map<String, Role> roleMap = readRoles(jsonNode);
readUsers(this.userNameToUser, jsonNode, roleMap);
return true;
} catch (IOException ex) {
return false;
}
}
示例9: deserialize
import com.fasterxml.jackson.databind.ObjectMapper; //导入方法依赖的package包/类
@Transient
public Exam deserialize() throws IOException {
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(content);
JsonNode node = mapper.readTree(json);
return JsonDeserializer.deserialize(Exam.class, node);
}
示例10: enumWithCustomJavaNames
import com.fasterxml.jackson.databind.ObjectMapper; //导入方法依赖的package包/类
@Test
@SuppressWarnings({ "unchecked" })
public void enumWithCustomJavaNames() throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, IOException {
ClassLoader resultsClassLoader = schemaRule.generateAndCompile("/schema/enum/enumWithCustomJavaNames.json", "com.example");
Class<?> typeWithEnumProperty = resultsClassLoader.loadClass("com.example.EnumWithCustomJavaNames");
Class<Enum> enumClass = (Class<Enum>) resultsClassLoader.loadClass("com.example.EnumWithCustomJavaNames$EnumProperty");
Object valueWithEnumProperty = typeWithEnumProperty.newInstance();
Method enumSetter = typeWithEnumProperty.getMethod("setEnumProperty", enumClass);
enumSetter.invoke(valueWithEnumProperty, enumClass.getEnumConstants()[2]);
assertThat(enumClass.getEnumConstants()[0].name(), is("ONE"));
assertThat(enumClass.getEnumConstants()[1].name(), is("TWO"));
assertThat(enumClass.getEnumConstants()[2].name(), is("THREE"));
assertThat(enumClass.getEnumConstants()[3].name(), is("FOUR"));
ObjectMapper objectMapper = new ObjectMapper();
String jsonString = objectMapper.writeValueAsString(valueWithEnumProperty);
JsonNode jsonTree = objectMapper.readTree(jsonString);
assertThat(jsonTree.size(), is(1));
assertThat(jsonTree.has("enum_Property"), is(true));
assertThat(jsonTree.get("enum_Property").isTextual(), is(true));
assertThat(jsonTree.get("enum_Property").asText(), is("3"));
}
示例11: deserialize_resultObjectHasColor
import com.fasterxml.jackson.databind.ObjectMapper; //导入方法依赖的package包/类
@Test
public void deserialize_resultObjectHasColor() throws Exception {
//given
ObjectMapper mapper = new ObjectMapper();
JsonNode actualObj = mapper.readTree("\"#FF00FF00\"");
ColorDeserializer deserializer = new ColorDeserializer(new BasicObjectSerializer());
//when
Color color = (Color) deserializer.deserialize(actualObj, mapper);
//then
Assertions.assertThat(color).isNotNull();
Assertions.assertThat(color.getRGB()).isEqualTo(Color.GREEN.getRGB());
}
示例12: searchEvents
import com.fasterxml.jackson.databind.ObjectMapper; //导入方法依赖的package包/类
/**
* Parse JSON from Open Agenda API get by the URL
*
* @param is Stream of {@link Event} from OpenAgenda
* @param source Name of source of this data
* @return a list of {@link Event}
* @throws NullPointerException if is or source is null
* @see Event
*/
default List<Event> searchEvents(InputStream is, String source) {
Objects.requireNonNull(is);
Objects.requireNonNull(source);
List<Event> events = new ArrayList<>();
ObjectMapper mapper = new ObjectMapper();
ObjectMapper fieldMapper = new ObjectMapper();
try {
JsonNode root = mapper.readTree(is);
//root
JsonNode recordsNode = root.path("records");
for (JsonNode knode : recordsNode) {
JsonNode fieldsNode = knode.path("fields");
String transform = "{\"fields\": [" + fieldsNode.toString() + "]}";
JsonNode rootBis = fieldMapper.readTree(transform);
JsonNode fieldsRoodNode = rootBis.path("fields");
for (JsonNode subknode : fieldsRoodNode) {
String latlon = subknode.path("latlon").toString();
String title = subknode.path("title").asText();
String description = subknode.path("description").asText() + " " + subknode.path("free_text").asText();
String dateStart = subknode.path("date_start").asText();
String dateEnd = subknode.path("date_end").asText();
String city = subknode.path("city").asText();
Event event = createEvent(latlon, title, description, dateStart, dateEnd, city, source);
pushIfNotNullEvent(events, event);
}
}
} catch (IOException e) {
LOGGER.error("Bad json format or tree cannot be read: {}", e);
}
return events;
}
示例13: jsonSerialization
import com.fasterxml.jackson.databind.ObjectMapper; //导入方法依赖的package包/类
/**
* Serialize a list of objects with a particular set of attributes
* @param view
* @return
* @throws IOException
*/
public JsonNode jsonSerialization(Class view) throws IOException
{
ObjectMapper mapper = new ObjectMapper();
DateFormat myDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
mapper.setDateFormat(myDateFormat);
mapper.disable(MapperFeature.DEFAULT_VIEW_INCLUSION);
ObjectWriter writer = mapper.writerWithView(view);
JsonNode response = mapper.readTree(writer.writeValueAsString(this));
return response;
}
示例14: getJsonNode
import com.fasterxml.jackson.databind.ObjectMapper; //导入方法依赖的package包/类
private JsonNode getJsonNode(String fileName) {
ObjectMapper mapper = new ObjectMapper();
try {
return mapper.readTree(TestUtil.getResourceAsStream(getResourceDir(), fileName));
} catch (IOException e) {
fail("Failed to parse JSON from file: " + e.getMessage());
}
return null;
}
示例15: getResponseListener
import com.fasterxml.jackson.databind.ObjectMapper; //导入方法依赖的package包/类
private Response.Listener<String> getResponseListener(final Listener l) {
return new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.i("RESPONSE", response);
ObjectMapper mapper = new ObjectMapper();
try {
JsonNode json = mapper.readTree(response);
l.onSuccess(json);
} catch (IOException e) {
l.onFailure("Invalid JSON: " + response);
}
}
};
}