ASP.NET MVC analysis with date of use of Jackson JSON library in Java

I am parsing JSON from the server in my Android application using the Jackson JSON library. However, parsing requests are interrupted whenever I get a DateTime, since it is in this format:

"/Date(1277931782420)/"

I know that 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 which format string to use)? Or I need to write my own DateFormat parser. So I would really appreciate if anyone could help with the sample code.

EDIT: Ok, see my answer for the full code.

+5
source share
2 answers

This turned out to be tougher than 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
    }
}

, :

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

, +, , .NET Ticks VS Java ticks - . - , - , , .

EDIT: , ServiceStack.Text , ISO8601. ( Jackson ISO8601, ). , , , , ( /​​ , , ):

@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();
    }
}
+5

, , Android, , :

"/Date(1277931782420)/"

Unix.

, / SimpleDateFormat. Long Date, , .

StackOverflow, : fooobar.com/questions/101638/...

+3

All Articles