当前位置: 首页 > 知识库问答 >
问题:

使用Jackson的ObjectMapper的JSON对象的顺序

谢志用
2023-03-14

我正在使用ObjectMapper进行java-json映射。

ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
ow.writeValue(new File( fileName +".json"), jsonObj);

这是我的java类:

public class Relation {

private String id;
private String source;
private String target;
private String label;
private List<RelAttribute> attributes;

public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

public String getSource() {
    return source;
}

public void setSource(String source) {
    this.source = source;
}

public String getTarget() {
    return target;
}

public void setTarget(String target) {
    this.target = target;
}

public String getLabel() {
    return label;
}
public void setLabel(String label) {
    this.label = label;
}

public void setAttributes(List<RelAttribute> attributes) {
    this.attributes = attributes;
}

public List<RelAttribute> getAttributes() {
    return attributes;
}

}

这就是我得到的:

{
    "id" : "-75da69d3-79c8-4000-a3d8-b10350a57a7e",
    "attributes" : [ {
      "attrName" : "ID",
      "attrValue" : ""
    }, {
      "attrName" : "Description",
      "attrValue" : "Primary Actor"
    }, {
      "attrName" : "Status",
      "attrValue" : ""
    } ],
    "label" : "new Label",
    "target" : "-46b238ac-b8b3-4230-b32c-be9707f8b691",
    "source" : "-daa34638-061a-45e0-9f2e-35afd6c271e0"
  }
{
    "id" : "-75da69d3-79c8-4000-a3d8-b10350a57a7e",
    "label" : "new Label",
    "target" : "-46b238ac-b8b3-4230-b32c-be9707f8b691",
    "source" : "-daa34638-061a-45e0-9f2e-35afd6c271e0",
    "attributes" : [ {
      "attrName" : "ID",
      "attrValue" : ""
    }, {
      "attrName" : "Description",
      "attrValue" : "Primary Actor"
    }, {
      "attrName" : "Status",
      "attrValue" : ""
    } ]

  }

我希望它的顺序与java声明中的顺序相同。有办法指定吗?也许有注释之类的东西?

共有1个答案

诸福
2023-03-14
@JsonPropertyOrder({ "id", "label", "target", "source", "attributes" })
public class Relation { ... }
 类似资料:
  • 问题内容: 我正在使用 ObjectMapper 进行java-json映射。 这是我的java类: 这就是我得到的: 所以我现在的问题是,如何获得此json输出: 我想要它与我的Java声明中的顺序相同。有没有办法指定它?也许带有注释或类似的东西? 问题答案:

  • 问题内容: 我正在实现RESTful Web服务,其中用户必须与请求一起发送签名的验证令牌,以便可以确保请求不会被中间人篡改。我当前的实现如下。 验证令牌是一个VerifData对象,它序列化为String,然后进行哈希处理和加密。 在我的服务中,我将要序列化的数据放入VerifData的实例中,然后使用Jackson ObjectMapper对其进行序列化,并与验证令牌一起传递给验证引擎。 但是

  • 我正在实现一个RESTful web服务,其中用户必须在请求的同时发送一个签名的验证令牌,这样我就可以确保请求没有被中间人篡改。我当前的实现如下所示。 验证令牌是一个VerifData对象,序列化为字符串,然后进行散列和加密。 有办法绕过这件事吗?我可以指定ObjectMapper要映射的属性的顺序吗(像按升序)?或者是否有任何其他方法可以最好地实现此验证步骤。客户端和服务器实现都是我开发的。我使

  • 我将json传递给ObjectMapper。JSON字符串如下所示: 我的类如下所示: 这种行为是意料之中的吗?如果是,有什么解决办法? 更新:添加了类描述。

  • 我正在尝试反序列化JSON对象,例如 Java子对象引用父对象的对象,例如: 像这样反序列化时,子对象#父对象不会指向父对象。我在做在线研究时读到了两种方法,但非似乎有效。 1.向类添加构造函数arg以设置父对象 执行此操作时,我得到错误: 2.使用和注释 此操作失败: JsonBackReference的JavaDoc说它不能应用于集合,所以它显然不起作用,但我想知道为什么在线上有这么多例子将它

  • 我在MongoDB集合中有以下文档,我希望将该文档映射回Kotlin对象。 我编写了一个自定义的反序列化器来读取UUID的二进制值,但它失败了。如有任何帮助,我们将不胜感激。 主应用程序。 序列化程序和反序列化程序: