首页 \ 问答 \ 如何在使用Jackson反序列化OffsetDateTime时保留偏移量(How to preserve the offset while deserializing OffsetDateTime with Jackson)

如何在使用Jackson反序列化OffsetDateTime时保留偏移量(How to preserve the offset while deserializing OffsetDateTime with Jackson)

在传入的JSON中,我有一个符合ISO8601标准的日期时间字段,包含区域偏移量。 我想保留这个偏移量,但不幸的是杰克逊默认为GMT / UTC,而反序列化这个字段(我从http://wiki.fasterxml.com/JacksonFAQDateHandling了解到)。

@RunWith(JUnit4.class)
public class JacksonOffsetDateTimeTest {

    private ObjectMapper objectMapper;

    @Before
    public void init() {
        objectMapper = Jackson2ObjectMapperBuilder.json()
            .modules(new JavaTimeModule())
            .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
            .build();
    }

    @Test
    public void test() throws IOException {
        final String json = "{ \"date\": \"2000-01-01T12:00:00.000-04:00\" }";
        final JsonType instance = objectMapper.readValue(json, JsonType.class);

        assertEquals(ZoneOffset.ofHours(-4), instance.getDate().getOffset());
    }
}


public class JsonType {
    private OffsetDateTime date;

    // getter, setter
}

我在这里得到的是:

java.lang.AssertionError: expected:<-04:00> but was:<Z>

如何使返回的OffsetDateTime包含原始偏移量?

我在杰克逊2.8.3。


In an incoming JSON, I have an ISO8601-compliant datetime field, containing zone offset. I'd like to preserve this offset, but unfortunately Jackson defaults to GMT/UTC while deserializing this field (what I understood from http://wiki.fasterxml.com/JacksonFAQDateHandling).

@RunWith(JUnit4.class)
public class JacksonOffsetDateTimeTest {

    private ObjectMapper objectMapper;

    @Before
    public void init() {
        objectMapper = Jackson2ObjectMapperBuilder.json()
            .modules(new JavaTimeModule())
            .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
            .build();
    }

    @Test
    public void test() throws IOException {
        final String json = "{ \"date\": \"2000-01-01T12:00:00.000-04:00\" }";
        final JsonType instance = objectMapper.readValue(json, JsonType.class);

        assertEquals(ZoneOffset.ofHours(-4), instance.getDate().getOffset());
    }
}


public class JsonType {
    private OffsetDateTime date;

    // getter, setter
}

What I'm getting here is:

java.lang.AssertionError: expected:<-04:00> but was:<Z>

How can I make the returned OffsetDateTime to contain the original Offset?

I'm on Jackson 2.8.3.


原文:https://stackoverflow.com/questions/40488002
更新时间:2022-11-14 10:11

最满意答案

欢迎来到SO!

你似乎在Pub / Sub和Collection.find之间感到困惑。

你应该首先意识到2是不同的机制,它们提供不同的功能。

  • Pub / Sub的确将数据从服务器发送到客户端的Minimongo数据库。 但是这些数据还没有显示出来。
  • Collection.find在您的服务器上针对您的实际MongoDB使用,在您的客户端针对您当地的Minimongo DB使用。

因此,在您的客户端上,一旦您正确订阅了您的服务器发布(通常在应用程序级别或模板级别/ onCreated钩子中),您可以直接在助手(或任何其他地方)中调用Jobs.find来获取文档,改变订阅(除非后者需要新的参数)。

你的评论代码应该没有问题:

return Job.find({'_id': { '$in': companyJobs }});

一般来说,避免在助手(如Meteor.subscribe )中进行任何昂贵的计算,因为助手可能会执行很多次而不会注意到它。 你的Meteor.subscribe('Companies')也应该进入模板级别(即在onCreated钩子)。

因此,不要在助手中执行if / else条件,只需在模板级别执行一次即可。 为了说明您需要使用另一个集合中其他文档的值,为什么不直接将公司的slug作为参数传递给您的Jobs订阅,并执行计算Server端? 或者甚至只是订阅一切,因为您目前的初始订阅似乎是这样做的。

然后,您的帮手将只使用Jobs.find ,这会查询您客户的本地minimongo数据库,从而让您的服务器不受干扰。


Welcome to SO!

You seem to be confused between Pub/Sub and Collection.find.

You should first realize that the 2 are different mechanisms, which provide different functionalities.

  • Pub/Sub indeed sends data from your Server into your Client's Minimongo database. But this data is not displayed yet.
  • Collection.find is used on your Server against your actual MongoDB, and on your Client against your local Minimongo DB.

Therefore on your client, once you have correctly subscribed to your server publication (typically at app level or template level / in onCreated hook), you can directly call Jobs.find in your helpers (or anywhere else) to get your documents, without having to change the subscription (unless the latter needs new parameters).

There should be nothing wrong with your commented code:

return Job.find({'_id': { '$in': companyJobs }});

In general, avoid any expensive computation in helpers (like Meteor.subscribe), as helpers may be executed many times without you noticing it. Your Meteor.subscribe('Companies') should also go to template level (i.e. in onCreated hook).

Therefore, instead of doing your if / else conditions in your helper, simply do it once at your template level. To account for your need to use a value from another document in another collection, why not just passing directly the company's slug as an argument to your Jobs subscription, and performing the computation Server-side? Or even just subscribing to everything, as your current initial subscription seems to do.

Then your helper will just use Jobs.find, which queries against your Client's local minimongo DB, leaving your Server unbothered.

相关问答

更多

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)