如何使用ObjectMapper将JSON属性转换为对象

huangapple go评论93阅读模式
英文:

How to convert a JSON Property to an Object using ObjectMapper

问题

以下代码可以实现相同的结果:

somethingDto = objectMapper.readValue(myJson.get("something").toString(), SomethingDTO.class);

请注意,如果“something”旁边还有更多属性,需要相应地调整代码以处理它们。

英文:

I use the following to convert a JSON into an Object:

JSON:

{
     "color": "blue"
}

Code:

somethingDto = objectMapper.readValue(myJson, SomethingDTO.class);

However, let's say that the JSON comes at the following format:

{
    "something": {
         "color": "blue"
    }
}

What code can achieve the same result?

Edit: There may be more properties alongside "something"

答案1

得分: 1

以下是您要翻译的代码部分:

// 创建一个根类,例如
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);
}
英文:

You should create a root class for it for example

public class RootDto {
     SomethingDTO somthing;

     public SomethingDTO getSomething() {
      return somthing;
     }
    
    
     public void setSomething(SomethingDTO somthing) {
      this.somthing = somthing;
     }
}

Then map your JSON to it

RootDto rootDto = objectMapper.readValue(myJson, RootDto.class);

Or you can use JsonNode

JsonNode rootNode = objectMapper.readTree(myJson);
JsonNode somethingNode = rootNode.get("something");
SomethingDTO somethingDto = objectMapper.convertValue(somethingNode, SomethingDTO.class);

Also, you can handle both of them in this way

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);
}

答案2

得分: 0

以下是代码部分的翻译:

@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")
        );
    }
}
英文:

Threre is an annotation called @JsonRootName which is similar to @XmlRootElement. That annotation indicates the name of the "root" wrapping.

@JsonRootName("something")
public class SomethingDto {

    String color;

    public String getColor() {
        return color;
    }

    public SomethingDto setColor(String color) {
        this.color = color;
        return this;
    }
}

After that, the fearure must be enabled:

ObjectMapper om = new ObjectMapper()
        .enable(SerializationFeature.WRAP_ROOT_VALUE)
        .enable(DeserializationFeature.UNWRAP_ROOT_VALUE);

Now, it will wrap / unwrap objects to desired root element(s).

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")
        );
    }
}

huangapple
  • 本文由 发表于 2023年4月4日 03:39:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/75923197.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定