我使用以下代码将JSON转换为Object:
JSON:
{
"color": "blue"
}
代码:
somethingDto = objectMapper.readValue(myJson, SomethingDTO.class);
但是,我们假设JSON的格式如下:
{
"something": {
"color": "blue"
}
}
哪些代码可以达到相同的结果?
编辑:"某某"旁边可能有更多属性
您应该为它创建一个根类,例如
public class RootDto {
SomethingDTO somthing;
public SomethingDTO getSomething() {
return somthing;
}
public void setSomething(SomethingDTO somthing) {
this.somthing = somthing;
}
}
然后将JSON映射到它
RootDto rootDto = objectMapper.readValue(myJson, RootDto.class);
或者你可以使用JsonNode
JsonNode rootNode = objectMapper.readTree(myJson);
JsonNode somethingNode = rootNode.get("something");
SomethingDTO somethingDto = objectMapper.convertValue(somethingNode, SomethingDTO.class);
同样,你可以这样处理它们
JsonNode rootNode = objectMapper.readTree(myJson);
JsonNode somethingNode = rootNode.get("something");
SomethingDTO somethingDto;
if (somethingNode != null) {
somethingDto = objectMapper.convertValue(somethingNode, SomethingDTO.class);
} else {
somethingDto = objectMapper.convertValue(rootNode, SomethingDTO.class);
}
有一个名为@JsonRootName
的注释,它与@XmlRootElement
类似。该注释指示"根"的名称。包装。
@JsonRootName("something")
public class SomethingDto {
String color;
public String getColor() {
return color;
}
public SomethingDto setColor(String color) {
this.color = color;
return this;
}
}
之后,必须启用该功能:
ObjectMapper om = new ObjectMapper()
.enable(SerializationFeature.WRAP_ROOT_VALUE)
.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
现在,它将绕/解绕对象到所需的根元素。
class WrapTest {
private static final ObjectMapper om = new ObjectMapper()
.enable(SerializationFeature.WRAP_ROOT_VALUE)
.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
//language=json
private static final String input = """
{
"something": {
"color" : "blue"
}
}
""";
@Test
void wrappedTest() throws JsonProcessingException {
var dto = om.readValue(input, SomethingDto.class);
Assertions.assertAll(
() -> assertNotNull(dto),
() -> assertEquals("blue", dto.getColor(), "color field mismatch")
);
}
}