使用Jackson的ObjectMapper解析具有动态类型

使用Jackson的ObjectMapper解析具有动态类型

本文介绍了使用Jackson的ObjectMapper解析具有动态类型(字符串或对象)的值的JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Jackson的新手,在确定处理动态的JSON文件的最佳方法时遇到了一些问题.我知道我可以使用流式或树状API来解决此问题,但这将涉及很多无法轻松维护的代码.例如,获取以下两个json文件:

I am new to Jackson and I am having some problems determining the best way to deal with processing JSON files that are dynamic in nature. I know I could solve the issue with the streaming or tree API, but this would involve a lot of code which will not be easily maintained. For example, take the following two json files:

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

{
   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类的数据对象如下:

the default behaviour of the first json object after being parsed, should add the URL to both service1 and service2 url lists in the subclass "URL". where the second allow specifying very specific urls to each. The data object for url class I was planning on use is as follows:

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参数.

There would also be some other parent class which would have a parameter for URL and other first level json parameters.

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

What is the best way to handle this in jackson?

推荐答案

答案:

在与Jackson一起努力以一种简单而优雅的方式完成我想做的事情之后,我最终切换到Gson库进行JSON解析.它使我能够为我的班级创建自定义反序列化器,这非常简单.

After struggling with Jackson to do what I want in a simple and elegant way, I ended up switching to Gson library for JSON parsing. it allowed me to create a custom deserializer for my class that was extremely easy.

可以在这里找到我做过的类似事情的例子:

An example of something similar that I did can be found here:

http://www.baeldung.com/gson-deserialization-guide

我很感谢Jackson的帮助和指导,但是这使我意识到Jackson不能满足我的需求.

I appreciate the help and guidance with Jackson, however it just made me realize that Jackson was just not going to meet my needs.

-Stewart

这篇关于使用Jackson的ObjectMapper解析具有动态类型(字符串或对象)的值的JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 13:38