java datetime json,如何解析.net DateTime作为json字符串接收到java的Date对象中

本文介绍如何在Java中使用Gson库解析从.NET Web服务接收到的JSON DateTime字符串,如"/Date(736032869080)/",并将其转换为Java的Date对象,无需修改服务器端代码。
摘要由CSDN通过智能技术生成

I'm receiving .NET's DateTime object as json string through my asmx webservice and trying to parse it with help of gson library. But seems like there's no support to parse .net style DateTime.

How can i parse it easily into java's Date object using Gson without much hassle?

the string i receive is like:

"DateOfBirth":"\/Date(736032869080)\/"

P.S. I would not like to make any modifications at server side to receive DateTime as a Long value

解决方案

Like this:

String json = "\"\\/Date(736032869080)\\/\"";

Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, new NetDateTimeAdapter()).create();

System.out.println("Date=" + gson.fromJson(json, Date.class));

class NetDateTimeAdapter extends TypeAdapter {

@Override

public Date read(JsonReader reader) throws IOException {

if (reader.peek() == JsonToken.NULL) {

reader.nextNull();

return null;

}

Date result = null;

String str = reader.nextString();

str = str.replaceAll("[^0-9]", "");

if (!TextUtils.isEmpty(str)) {

try {

result = new Date(Long.parseLong(str));

} catch (NumberFormatException e) {

}

}

return result;

}

@Override

public void write(JsonWriter writer, Date value) throws IOException {

// Nah..

}

}

Or use this example instead & follow the "Dealing with WCF Microsoft JSON Dates" chapter.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
0; passband_attenuation = 0; stopband_attenuation = 0; % 打开文件 function OpenFile(~, ~) [filename, path] = uigetfile({'*.wav;*.mp3;*.aac;*.wma在 C# ,可以使用 `JsonConvert.DefaultSettings` 属性来设置全局的 JSON 序列化和反序列化设置', '音频文件'; '*.*', '所有文件'}, '选择文件'); if filename ~= 0 file = fullfile(path。通过设置 `JsonSerializerSettings` 对象的 `DateFormatString` 属性,可以指定在序列化 `DateTime` 对象, filename); [~, ~, ext] = fileparts(file); if strcmp(ext, '.wav') || strcmp(ext, '.mp3时使用的日期格式。 以下是一个示例,演示如何设置全局的 `JsonSerializerSettings` 对象: ```csharp JsonConvert.DefaultSettings = () => new JsonSerializerSettings { DateFormatString = "yyyy-MM-dd HH:mm:ss", DateTimeZoneHandling = DateTimeZoneHandling.Local }; ``` 在这个示例,我们设置了 `JsonConvert.DefaultSettings` 为一个返回 `JsonSerializerSettings` 对象的 lambda 表达式。在 `JsonSerializerSettings` 对象,我们指定了需要使用的日期格式和时区处理方式。这将确保在序列化 `DateTime` 对象时,使用指定') || strcmp(ext, '.aac') || strcmp(ext, '.wma') [data, rate] = audioread(file); 的日期格式和时区处理方式。 需要注意的是,这个设置是全局有效的,将影响所有使用 ` signal_data = data; sample_rate = rate; set(findobj(fig, 'Tag', 'FileName'), 'String', filename); JsonConvert` 进行序列化和反序列化的操作。如果在某些情况下需要使用不同的日期 set(findobj(fig, 'Tag', 'SampleRate'), 'String', num2str(sample_rate)); plot_signal(signal_data,格式或时区处理方式,可以在序列化或反序列化时进行覆盖。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值