如何为这个 JSON 创建 Java 的 POJO 类?

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

How to make java POJO for this json?

问题

我对于在给定的 JSON 对象中,当键值为数字时如何创建一个 POJO(普通的 Java 对象)感到好奇。

  1. {
  2. "id": 1,
  3. "options": {
  4. "1": "a",
  5. "2": "b",
  6. "3": "c",
  7. "4": "e"
  8. }
  9. }

正如您所看到的,"options" 中的键是数字值,然而在 Java 中变量名不能为数字。要将其转化为 Java POJO,您可以使用 @JsonProperty 注解来处理这种情况。以下是一个示例:

  1. import com.fasterxml.jackson.annotation.JsonProperty;
  2. import java.util.Map;
  3. public class MyPOJO {
  4. private int id;
  5. private Map<String, String> options;
  6. @JsonProperty("id")
  7. public int getId() {
  8. return id;
  9. }
  10. @JsonProperty("id")
  11. public void setId(int id) {
  12. this.id = id;
  13. }
  14. @JsonProperty("options")
  15. public Map<String, String> getOptions() {
  16. return options;
  17. }
  18. @JsonProperty("options")
  19. public void setOptions(Map<String, String> options) {
  20. this.options = options;
  21. }
  22. }

在这个示例中,我们使用了 Jackson 库的 @JsonProperty 注解,将 JSON 中的键映射到 Java 类的字段或方法。这样您就可以在 Java 中表示这样的 JSON 结构,并且可以正常使用字段名为数字的键。

英文:

I'm curious about how to make a POJO when the key values are numeric as given in the given JSON object.

  1. {
  2. &quot;id&quot; : 1,
  3. &quot;options&quot;: {
  4. &quot;1&quot;: &quot;a&quot;,
  5. &quot;2&quot;: &quot;b&quot;,
  6. &quot;3&quot;: &quot;c&quot;,
  7. &quot;4&quot;: &quot;e&quot;
  8. }
  9. }

as you can see options have numeric values as a key, so how to make java POJO out of it, as a variable name cannot be numeric.

答案1

得分: 0

使用类似以下的代码:

  1. public class MyPojo {
  2. private int id;
  3. private Map<Integer, String> options;
  4. }
英文:

Use something like this

  1. public class MyPojo {
  2. private int id;
  3. private Map&lt;Integer, String&gt; options;
  4. }

huangapple
  • 本文由 发表于 2020年8月15日 18:43:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/63425122.html
匿名

发表评论

匿名网友

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

确定