Wednesday, August 3, 2016

Dates in WCF - JavaScript communication over JSON

Hi,

today we had really big troubles with WCF and javascript communication. We wanted to send dates over the wire and use its value for additional libraries (which rely on type Date). After hours of playing around I finally solved it with JSON.parse.

Different approaches starting from overriding the WCF object serializer till writing a custom json parser libraries had been tried but finally all these are very unstable.

Resources I found to solve the problem
- Hanselman ... describing my problem
Stackoverflow ... similar issue (solution mentioned)
- Documentation ... after knowing the solution a perfect page :-)

JavaScript/HTML testproject follows...

kind regards,
Daniel




 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<html><head></head><body>

<script>
function test() {

var objectString = '{"name" : "Daniel", "date" : "\/Date(1293034567877)\/"}';

//___________________________________________________________________________________
//

var objectDataWithParse =  JSON.parse(objectString);

var objectDataWithDate = {
    "name": objectDataWithParse.name,
    "date": new Date(parseInt(objectDataWithParse.date.substr(6, objectDataWithParse.date.length-8)))
};

function parseReviver(key, value) {
    var a;
    if (typeof value === 'string') {
        if(value.substr(0, 6) == '\/Date(') {

            alert(value.substr(6, value.length-8));
            return new Date(parseInt(value.substr(6, value.length-8)))
        }
    }
    return value;
};

var objectDataWithReviver = JSON.parse(objectString, parseReviver);

//___________________________________________________________________________________
//

var outObj = {};
outObj = objectDataWithDate;
outObj = objectDataWithParse;
outObj = objectDataWithReviver;

//___________________________________________________________________________________
//

document.getElementById('outputDIV_json').innerHTML = objectString;
document.getElementById('outputDIV_name').innerHTML = outObj.name;
document.getElementById('outputDIV_date').innerHTML = outObj.date;

};
</script>

<div>
<button onclick="test()" >test</button>
</div>
<hr />
<div id="outputDIV_json" ></div>
<div id="outputDIV_name" style="float:left;margin-right: 5px;margin-top: 5px; background: lightgreen"></div>
<div id="outputDIV_date" style="float:left;margin-right: 0px;margin-top: 5px; background: orange"></div>

</body></html>