【问题标题】:How to convert string to JSON using ObjectMapper? [closed]如何使用 ObjectMapper 将字符串转换为 JSON? [关闭]
【发布时间】:2020-11-06 13:20:08
【问题描述】:

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

    ObjectMapper mapper = new ObjectMapper();
    User user = new User();
    user.set_id(1);
    int id = 2;
    user.setIndex("{\"_id\":" + id + "}");
    mapper.writeValue(new File("user.json"), user);

输出: {"index":{"_id":"1"}} {"index":{"_id":"2"}}

【问题讨论】:

  • 你尝试过使用 mapper.writeValueAsString(user) 吗?
  • 能否请您发布用户pojo类结构?

标签: java jackson fasterxml


【解决方案1】:

首先,

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

[{"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

【讨论】:

    【解决方案2】:

    输出看起来像用户对象的结构:

    {"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}}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-19
      • 1970-01-01
      • 1970-01-01
      • 2014-01-08
      • 1970-01-01
      • 2018-05-02
      • 1970-01-01
      相关资源
      最近更新 更多