【问题标题】:Java JSONObject for .net webservice deserialisation to DateTime()Java JSONObject 用于将 .net Web 服务反序列化为 DateTime()
【发布时间】:2010-07-15 14:58:08
【问题描述】:

我有一个 .net Web 服务,它应该通过 json 与 Java 应用程序通信。

现在我在服务器端有一个方法,如下所示:

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public DateTime GetDate(DateTime input)
    {
        return input;
    }

我可以从 C# 应用程序发送接收 DateTime 值。 Date 值被序列化为:

\/Date(1279176056000)\/

其中数字定义为自纪元以来的秒数。 因此,如果我想调用该服务,我的 json 请求字符串必须如下所示:

{"input":"\/Date(1279176056000)\/"}

但是,我不知道如何使用 Java 端的 json.org.* 类来实现这一点。
问题:如果我使用此代码:

JSONObject json = new JSONObject();
json.put("input", "\\/Date(1279176056000)\\/");

JSONObject 足够聪明,可以在通过线路发送之前对字符串本身进行转义,所以我得到:

{"input":"\\/Date(1279176056000)\\/"}

在服务器端反序列化期间导致异常:

System.FormatException: \/Date(1279183256000)\/ is not a valid value for DateTime
bei System.ComponentModel.DateTimeConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value)
bei System.Web.Script.Serialization.ObjectConverter.ConvertObjectToTypeInternal(Object o, Type type, JavaScriptSerializer serializer, Boolean throwOnError, Object& convertedObject)
bei System.Web.Script.Serialization.ObjectConverter.ConvertObjectToTypeMain(Object o, Type type, JavaScriptSerializer serializer, Boolean throwOnError, Object& convertedObject)
bei System.Web.Script.Serialization.ObjectConverter.ConvertObjectToType(Object o, Type type, JavaScriptSerializer serializer)
bei System.Web.Script.Services.WebServiceMethodData.StrongTypeParameters(IDictionary`2 rawParams)
bei System.Web.Script.Services.WebServiceMethodData.CallMethodFromRawParams(Object target, IDictionary`2 parameters)
bei System.Web.Script.Services.RestHandler.InvokeMethod(HttpContext context, WebServiceMethodData methodData, IDictionary`2 rawParams)
bei System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)

长话短说:如何将反斜杠作为参数传递给 JSONObject 而不会转义?

好吧,你可能认为我只是自己构建 JSON 字符串,但我真的想发送和接收包含 Date 属性的更复杂的对象/数组,我不想自己处理整个 JSON 生成。

【问题讨论】:

  • 您不喜欢从 json 日期时间对象中制作一个常规的日期时间对象然后发送它吗?
  • 我希望能够将我的 web 服务中的方法与 JSON 以及来自 c# 的 SOAP 一起使用,并且我希望具有类型安全性,因此我的参数必须是 DateTime。
  • 好的,在您发表评论后,我考虑了一下。我非常专注于以预期格式发送日期,以至于我没有想出以不同方式格式化日期的想法(date.toString() 首先产生了格式异常,这就是我想出的原因模拟网络格式的想法)。但这很简单:date.toGMTString() 成功了。
  • 您可能想要删除 C# 标记,因为据我所知,答案都是 Java 特定的。

标签: c# java json datetime


【解决方案1】:

我遇到了同样的问题。在提交值之前,我做了一个 replaceAll。对于 Java 和 RegEx,它有很多斜线需要正确转义。

JSONObject json = new JSONObject();
json.put("input", "\\/Date(1279176056000)\\/");

String stringToSubmit = json.toString().replaceAll("\\\\\\\\", "\\\\");

【讨论】:

  • 我已经忘记了这个问题。几十年前我自己解决了它,并添加了一个很好的解决方案。感谢您的更新。
【解决方案2】:

这是我自己的解决方案:

import java.util.Date;

public class DateConverter {

    private static long TicksToMillisOffset = 621355968000000000L;
    private static long TicksPerMillisecond = 10000L;

    public static Long toTicks(Date date)
    {
        if (date == null) return null;

        int offset = date.getTimezoneOffset() * 60;
        long ms = date.getTime();

        return (ms + offset) * TicksPerMillisecond + TicksToMillisOffset;   
    }

    public static Date fromTicks(Long ticks)
    {
        return ticks == null 
            ? null
            : new Date((ticks - TicksToMillisOffset) / TicksPerMillisecond);
    }

    public static String toJSONString(Date date) {
        return date != null ? date.toGMTString() : null;
    }

    public static Date fromJSONString(String string) {

        // expected: "/Date(secondssinceepoch)/"
        if (string.matches("^/Date\\(\\d+\\)/$")) {
            String value = string.replaceAll("^/Date\\((\\d+)\\)/$", "$1");
            return new Date(Long.valueOf(value));
        }
        else {
            return new Date(Date.parse(string));
        }

    }

}

用法:

// deserialisation:
JSONObject json = GetJSONObjectFromNetWebService();

Poco item = new Poco();
item.id = json.getInt("Id");
item.name = json.GetString("Name");
item.dateValue = DateConverter.fromJSONString(json.getString("DateValue"));

// serialisation
JSONObject json = new JSONObject();

Poco item = GetPocoFromSomeWhereElse();
json.put("Id", item.id);
json.put("Name", item.name);
json.put("DateValue", DateConverter.toJSONString(item.dateValue));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-23
    • 2017-08-15
    • 1970-01-01
    • 2018-11-23
    相关资源
    最近更新 更多