【问题标题】:How to write Java class to fetch the object from Json which doesn't have fixed fields?如何编写 Java 类以从没有固定字段的 Json 中获取对象?
【发布时间】:2014-11-10 09:49:12
【问题描述】:

我需要 Java 类来满足以下要求,并且它应该兼容 Jackson 使用 Object Mapper 进行的解析。

Json 格式如下:

[
 { 
   "name" : "Snehal",
   "property1" : "value11",
   "property2" : "value12",
   "property3" : "value13",

 },
 {
   "name" : "Masne",
   "property1" : "value21",
   "property2" : "value22",
   "property3" : "value23",

},
]

在上面的 Json 中,没有。的属性不固定,这意味着可能有属性 4、5、6 等

对应的Java类可以认为如下:

Class MyClass
{

  String name;

  List<String> properties;

 // getters, setters, etc

}

但这并不能解决问题,因为在这种情况下,Json 会生成类似以下格式的内容:

[ 
 {
   "name" : "Snehal",
   [
      {"property" : "value1" },
      {"property" : "value1" },
      {"property" : "value1" }
   ]
 },

 {
   .... []
 }

]

如何实现Java类来实现指定Json格式的数据?

【问题讨论】:

标签: java json jackson pojo


【解决方案1】:

您可以使用@JsonAnyGetter/@JsonAnySetter 注释来标记您的类除了声明的字段之外还有“额外”属性。

这是一个例子:

public class JacksonAnyGetter {

    static final String JSON = " { \n" +
            "   \"name\" : \"Snehal\",\n" +
            "   \"property1\" : \"value11\",\n" +
            "   \"property2\" : \"value12\",\n" +
            "   \"property3\" : \"value13\"\n" +
            "\n" +
            " }";

    static class Bean {
        public String name; // we always have name
        private Map<String, Object> properties = new HashMap<>();

        @JsonAnySetter
        public void add(String key, String value) {
            properties.put(key, value);
        }

        @JsonAnyGetter
        public Map<String, Object> getProperties() {
            return properties;
        }

        @Override
        public String toString() {
            return "Bean{" +
                    "name='" + name + '\'' +
                    ", properties=" + properties +
                    '}';
        }
    }

    public static void main(String[] args) throws IOException {
        final ObjectMapper mapper = new ObjectMapper();
        final Bean bean = mapper.readValue(JSON, Bean.class);
        System.out.println(bean);
        final String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(bean);
        System.out.println(json);
    }
}

输出:

Bean{name='Snehal', properties={property3=value13, property2=value12, property1=value11}}
{
  "name" : "Snehal",
  "property3" : "value13",
  "property2" : "value12",
  "property1" : "value11"
}

【讨论】:

  • 完美!感谢 Alexey 的解决方案! :-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-12-31
  • 1970-01-01
  • 2021-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多