使用 Jackson 的 ObjectMapper 解析具有动态类型(字符串或对象)的值的 JSON

2023-12-31

我是 Jackson 的新手,在确定处理动态 JSON 文件的最佳方法时遇到一些问题。我知道我可以使用流或树 API 来解决问题,但这会涉及大量不易维护的代码。例如,采用以下两个 json 文件:

{
   something: "somethingValue"
   somethingelse: "anotherValue"
   url: "http://something.com"
}

and

{
   something: "somethingValue"
   somethingelse: "anotherValue"
   url: {
           service1: [
              "http://something.com",
              "https://something.com" ],
           service2: [
              "http://something2.com",
              "https://something2.com" ],
        }
}

解析后第一个 json 对象的默认行为应将 URL 添加到子类“URL”中的 service1 和 service2 url 列表中。其中第二个允许为每个指定非常具体的 url。我计划使用的 url 类的数据对象如下:

public class url {

   // ideally, I would use the java.net.URL instead of String
   public List<String> service1;    
   public List<String> service2;

   // also includes getter/setters using a fluent style
   ...
}

还有一些其他父类,其中包含 URL 参数和其他第一级 json 参数。

在杰克逊处理这个问题的最佳方法是什么?


第二个不是有效的 JSON,这是:

{
   "something": "somethingValue",
   "somethingelse": "anotherValue",
   "url": {
           "service1" : [
              "http://something.com",
              "https://something.com" ],
           "service2" : [
              "http://something2.com",
              "https://something2.com" ]
        }
}

您可以使用 A 类创建/使用它,如下所示

class A{
 String something;
 String somethingElse;
 B url;
}

class B{
 Str service1;
 List<String> service2;
}

无论如何,要动态实现任何目标,您必须将其放入列表中,因此您可以这样做,而不是上面的解决方案

class A{
 String something;
 String somethingElse;
 B url;
}

class B{
 List<C> services;
}    

class C{
  List<String> service;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 Jackson 的 ObjectMapper 解析具有动态类型(字符串或对象)的值的 JSON 的相关文章

随机推荐