简体   繁体   English

解析ASP.NET MVC使用Java中的Jackson JSON库返回日期

[英]Parsing ASP.NET MVC returned date using Jackson JSON library in Java

I am parsing JSON from server in my Android application by using Jackson JSON library. 我使用Jackson JSON库在我的Android应用程序中解析服务器中的JSON。 However, parsing requests fail whenever I receive DateTime since it's in this format: 但是,每当我收到DateTime时,解析请求都会失败,因为它采用以下格式:

"/Date(1277931782420)/"

I know I should do something like: 我知道我应该这样做:

ObjectMapper om = new ObjectMapper();
om.setDateFormat(new TicksSinceFormat());

But I have no idea if I can use SimpleDateFormat at all (and what format string would I use?) or I need to write my own DateFormat parser. 但是我根本不知道我是否可以使用SimpleDateFormat(我会使用什么格式的字符串?)或者我需要编写自己的DateFormat解析器。 So, I would seriously appreciate if somebody could help with code example. 所以,如果有人可以帮助代码示例,我会非常感激。

EDIT: OK, see my answer for complete code. 编辑:好的,请参阅我的答案以获取完整的代码。

This proved to be tougher then I expected: 事实证明这比我预期的要困难:

public class TicksSinceFormat extends DateFormat {
    @Override
    public StringBuffer format(Date date, StringBuffer buffer, FieldPosition field) {
        long millis = date.getTime();

        return new StringBuffer("/Date(" + millis + ")/");
    }

    @Override
    public Date parse(String string, ParsePosition position) {
        int start = string.indexOf("(") + 1;
        int end = string.indexOf(")");

        String ms = string.substring(start, end);
        Date date = new Date(Long.parseLong(ms));

        position.setIndex(string.length() - 1); // MUST SET THIS
        return date;
    }

    @Override
    public Object clone() {
        return new TicksSinceFormat(); // MUST SET THIS
    }
}

Using class is then extremely simple, just do: 使用类非常简单,只需:

ObjectMapper om = new ObjectMapper();
om.setDateFormat(new TicksSinceFormat())

I presume that this can be coded better + that I'll need to deal with differences when it comes to .NET Ticks VS Java ticks - but for now this'll do. 我认为这可以更好地编码+我需要处理.NET Ticks VS Java ticks的差异 - 但是现在这样做了。 If somebody has better solution or more insight into mentioned problems I'll deal with later - feel free to post and I'll mark your answer as correct one if it's better. 如果某人有更好的解决方案或更深入地了解我将在稍后处理的问题 - 请随时发布,如果情况好转,我会将您的答案标记为正确。

EDIT: As I've explained in this question & answer I've switched to ServiceStack.Text library on the server and it returns different, ISO8601 format. 编辑:正如我在这个问题和答案中解释的那样,我已经切换到服务器上的ServiceStack.Text库,它返回不同的ISO8601格式。 For that format I'm using slightly different parsing (since Jackson has trouble parsing ISO8601 that contains milliseconds). 对于那种格式,我使用稍微不同的解析(因为Jackson在解析包含毫秒的ISO8601时遇到问题)。 Of course, as with other code I'm posting - let me know if you have better version (just please post code / edit this post, rather than resorting to philosophical rhetoric on how it should be done): 当然,和我发布的其他代码一样 - 请告诉我你是否有更好的版本(请发布代码/编辑这篇文章,而不是诉诸于如何做的哲学修辞):

@SuppressLint("SimpleDateFormat")
public class JacksonSimpleDateFormat extends SimpleDateFormat {
    public JacksonSimpleDateFormat() {
        if (mParser == null) {
            mParser = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
            mParser.setTimeZone(TimeZone.getTimeZone("UTC"));
        }
    }

    @Override
    public StringBuffer format(Date date, StringBuffer buffer, FieldPosition field) {
        return mParser.format(date, buffer, field);
    }

    private static SimpleDateFormat mParser;
    @Override
    public Date parse(String string, ParsePosition position) {
        String str = string.split("\\.")[0];

        Date date = null;
        try {
            date = mParser.parse(str);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        position.setIndex(string.length() - 1);
        return date;
    }

    @Override
    public Object clone() {
        return new JacksonSimpleDateFormat();
    }
}

I may be wrong on this, as I haven't gotten very far into Android development, but the format you presented: 我可能错了,因为我没有深入到Android开发,但你提出的格式:

"/Date(1277931782420)/"

Appears to be Unix epoch time. 似乎是Unix纪元时代。

If that is the case, you would not want/need to use SimpleDateFormat . 如果是这种情况,您不希望/需要使用SimpleDateFormat Instead, try creating a Long from it and passing to the Date constructor, accounting for whether it is seconds or milliseconds-based epoch value. 相反,尝试从中创建一个Long并传递给Date构造函数,考虑它是基于秒还是毫秒的纪元值。

Here is a StackOverflow post that provides the code for doing so: https://stackoverflow.com/a/535017/463196 这是一个StackOverflow帖子,提供了执行此操作的代码: https//stackoverflow.com/a/535017/463196

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM