如何使用ObjectMapper将字符串转换为JSON?

问题描述

我需要使用Java使用ObjectMapper的以下JSON格式。

AWS-JoinDirectoryServiceDomain

输出: {“ index”:{“ _ id”:“ 1”}} {“ index”:{“ _ id”:“ 2”}}

解决方法

首先,

如果是用户列表,输出应该是

[{"index":{"_id":"1"}},{"index":{"_id":"2"}}]

此外,如果您想以这种方式实现,我会说在基础pojo上使用另一个Pojo,以便您可以根据需要轻松地序列化和反序列化json。这样的事情可能对您有用

-----------------------------------com.example.Index.java-----------------------------------

package com.example;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"index"
})
public class Index {

@JsonProperty("index")
public User index;

}
-----------------------------------com.example.Index_.java-----------------------------------

package com.example;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"_id"
})
public class User {

@JsonProperty("_id")
public String id;

}

现在可以转换为所需格式了

mapper.writeValueAsString(index); //will return a string
,

输出将类似于User对象的结构:

{"id":1,"index":"{\"_id\":2}"}

不是想做的事。您的输出格式显然不正确。您要显示的内容看起来像一个列表。您必须将用户对象包装在列表中才能获得所需的结果。

此外,“ id”也不会出现在您的输出格式中。您是否要直接在索引中包含id值?您需要重新考虑您的对象或创建另一个对象以填充输出。

一个轨道可能是通过添加以下内容来更改id字段上json的名称:

@JsonProperty("_id")
private int id;

要使用您的用户格式,请尝试以下操作:

public static void main(String[] args) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    User user = new User();
    user.setId(1);

    mapper.writeValue(new File("user.json"),new Index(user));
  }

  @Data
  public static class User {
    @JsonProperty("_id")
    private int    id;

    public User() {

    }
  }

  @Data
  public static class Index {
    @JsonProperty("index")
    private User user;

    public Index(User user) {
      this.user = user;
    }
  }

对我来说,这绝对是您想要的列表,输出将针对一个对象:

{"index":{"_id":1}}